在特定目录的上下文中运行python unittest

科里·科尔

在我的python应用程序中,我打开了mp3文件,其中包含程序启动位置的相对路径。为简单起见,我对此处项目中存在的问题进行了最小化复制

基本上,我有这样的结构:

src
└─ main.py
test
└─ test_main.py

main.py我有一个简单的功能,打印并返回当前的工作目录:

def get_cwd() -> str:
    directory = os.path.basename(os.getcwd())
    print('Current directory =', directory)
    return directory

因此,如果我cd进入该src文件夹并运行,python main.py我会看到:

Current directory = src

这是理想的行为,因为在我的程序中mp3文件的文件路径是相对于的src

当我尝试编写测试时会出现问题。我似乎无法得到这样的测试通过,不管是什么我传递给--start-directory--top-level-directory

def test_get_cwd(self):
    print('testing get_cwd()')
    current_dir = get_cwd()
    self.assertIsNotNone(current_dir)
    self.assertEqual(current_dir, 'src')

问题:如果将测试保存到其他目录,该如何将它们像在特定目录的上下文中一样运行?

限制条件:

  • 测试必须使用绝对路径导入,如我的示例所示: from src.main import get_cwd
贾维尔德

有一个os功能可以更改目录,然后尝试添加os.chdir('src')到测试中。

import unittest
import os

from src.main import get_cwd


class TestMain(unittest.TestCase):

    def test_get_cwd(self):
        os.chdir('src')
        print('testing get_cwd()')
        current_dir = get_cwd()
        self.assertIsNotNone(current_dir)
        self.assertEqual(current_dir, 'src')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章