Py学习  »  Python

为django测试用例模拟整个python模块

ediordna • 6 年前 • 1983 次点击  

我正在尝试模拟credentials.py模块,它是 不存在的 在使用管道中的gitlab runner运行测试期间(凭据位于.gitignore上)。所以实际上“mock”必须创建credentials.py。

编辑:我想问题是django系统检查( https://docs.djangoproject.com/en/2.1/ref/checks/ ,它检查是否所有导入都可用。

edit2:我找到了一种方法来防止测试环境中的导入错误。但我不确定这是否是为了编写好代码而做出的选择,这就是为什么我没有使用应答函数。我发现以下StackOverflow问题: Python: Mock a module without importing it or needing it to exist 并使用第一个答案中的建议在 views.py :

try:
   from battery_upgrade_web import credentials
except ImportError:
   from battery_upgrade_web import credentials_example as credentials

gitlab中存在凭据示例,该示例为空。这样就可以在gitlab runner中成功地执行所有测试。

我的 test_views.py 看起来像这样:

@patch('battery_upgrade_web.views.BatteryUpgradeView.credentials', new=credentials_example)
class IndexViewTest(TestCase):

    @patch('battery_upgrade_web.views.BatteryUpgradeView.credentials', new=credentials_example)
    def setUp(self):
        # A client simulates a user interacting with the code at the view level
        # Lot of working mocks
        self.c = Client()

    @patch('battery_upgrade_web.views.credentials', new=credentials_example)
    def test_valid_data(self):
        resp = self.c.post('/', data={'parameter': 324})

我的 VIEW :

from battery_upgrade_web import credentials

class BatteryUpgradeView(generic.TemplateView):
    def post(self, request, *args, **kwargs):
    #lot of code to execute

我的问题是,我不仅可以修补credentials.py中的变量,还必须修补整个模块并用credentials\example.py替换它。上面的解决方案在本地使用现有credentials.py,它还模拟credentials.py,并在测试期间用credentials_example.py替换它。但是当我删除credentials.py时,测试在运行时抛出以下错误消息 >python web/manage.py test battery_upgrade_web :

Creating test database for alias 'default'...
Traceback (most recent call last):
File "web/manage.py", line 16, in <module>
    execute_from_command_line(sys.argv)
    # lot of tracebacks
File "C:\Users\e\AppData\Local\Continuum\anaconda2\envs\BatteryUpgrade36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_loal
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\e\Projects\BatteryUpgrade\web\battery_upgrade_web\urls.py", line 21, in <module>
from battery_upgrade_web.views import BatteryUpgradeView
File "C:\Users\e\Projects\BatteryUpgrade\web\battery_upgrade_web\views.py", line 11, in <module>
from battery_upgrade_web import credentials
ImportError: cannot import name 'credentials'

看起来,在测试正常启动之前有一个模块的导入。但是怎么嘲笑呢?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40835
文章 [ 1 ]  |  最新文章 6 年前