在我的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] 删除。
我来说两句