我专门使用 Django 和 Pytest 来运行测试套件,并尝试测试当用户访问网站时特定表单是否显示预期数据(集成测试)。
这个特定的视图使用了一个存储过程,我在嘲笑它,因为测试永远无法访问它。
我的测试代码如下所示:
#test_integrations.py
from my_app.tests.data_setup import setup_data, setup_sb7_data
from unittest.mock import patch
...
# Setup to use a non-headless browser so we can see whats happening for debugging
@pytest.mark.usefixtures("standard_browser")
class SeniorPageTestCase(StaticLiveServerTestCase):
"""
These tests surround the senior form
"""
@classmethod
def setUpClass(cls):
cls.host = socket.gethostbyname(socket.gethostname())
super(SeniorPageTestCase, cls).setUpClass()
def setUp(self):
# setup the dummy data - this works fine
basic_setup(self)
# setup the 'results'
self.sb7_mock_data = setup_sb7_data(self)
@patch("my_app.utils.get_employee_sb7_data")
def test_senior_form_displays(self, mock_sb7_get):
# login the dummy user we created
login_user(self, "futureuser")
# setup the results
mock_sb7_get.return_value = self.sb7_mock_data
# hit the page for the form
self.browser.get(self.live_server_url + "/my_app/senior")
form_id = "SeniorForm"
# assert that the form displays on the page
self.assertTrue(self.browser.find_element_by_id(form_id))
# utils.py
from django.conf import settings
from django.db import connections
def get_employee_sb7_data(db_name, user_number, window):
"""
Executes the stored procedure for getting employee data
Args:
user_number: Takes the user_number
db (db connection): Takes a string of the DB to connect to
Returns:
"""
cursor = connections[db_name].cursor()
cursor.execute(
'exec sp_sb7 %s, "%s"' % (user_number, window.senior_close)
)
columns = [col[0] for col in cursor.description]
results = [dict(zip(columns, row)) for row in cursor.fetchall()]
return results
# views.py
from myapp.utils import (
get_employee_sb7_data,
)
...
###### Senior ######
@login_required
@group_required("user_senior")
def senior(request):
# Additional Logic / Getting Other Models here
# Execute stored procedure to get data for user
user_number = request.user.user_no
results = get_employee_sb7_data("production_db", user_number, window)
if not results:
return render(request, "users/senior_not_required.html")
# Additional view stuff
return render(
request,
"users/senior.html",
{
"data": data,
"form": form,
"results": results,
},
)
如果我自己运行这个测试:
pytest my_app/tests/test_integrations.py::SeniorPageTestCase
测试通过没有问题。浏览器出现了——表单显示了我们所期望的虚拟数据,并且一切正常。
但是,如果我运行:
pytest my_app
所有其他测试都运行并通过 - 但此类中的所有测试都失败了,因为它没有修补函数。
它尝试调用实际的存储过程(由于它不在生产服务器上而失败)并且它失败了。
为什么当我专门调用该 TestCase 时它会正确修补 - 但当我只是pytest
在应用程序或项目级别上运行时不能正确修补?
我很茫然,不知道如何很好地调试它。任何帮助表示赞赏