无法使用pytests的辅助类

时间:2018-01-31 07:55:40

标签: django pytest pytest-django

助手类

    class UserBuilder:
        def __init__(self):
            self.user = CustomUser.objects.get(email='random_email@test.com')

        def get_user(self):
            return self.user

测试类

    @pytest.mark.django_db
    @pytest.mark.parametrize('(user, output)', [
        (user_builder.change_bank_billdesk_bank_id(bank_name="IDN").get_user(), -1),
        (user_builder.change_bank_billdesk_bank_id(bank_name="IDB").get_user(), -1),
        (user_builder.change_bank_billdesk_bank_id(bank_name="SBI").get_user(), 1)
    ])
    def test_users_with_different_banks(self, user, output):

错误记录

    tests/trial.py:16: in <module>
        @pytest.mark.django_db
    tests/trial.py:100: in TestFunction
        user_builder = UserBuilder()
    tests/builder/user_builder.py:13: in __init__
        self.user = CustomUser.objects.get(email='random_email@test.com')
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/manager.py:127: in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:328: in get
        num = len(clone)
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:144: in __len__
        self._fetch_all()
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:965: in _fetch_all
        self._result_cache = list(self.iterator())
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/query.py:238: in iterator
        results = compiler.execute_sql()
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py:838: in execute_sql
        cursor = self.connection.cursor()
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/backends/base/base.py:162: in cursor
        cursor = self.make_debug_cursor(self._cursor())
    ../.virtualenvs/local_dev/local/lib/python2.7/site-packages/django/db/backends/base/base.py:135: in _cursor
        self.ensure_connection()
    E   Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

互联网上没有适当的解决方案,所以我尝试了所遇到的任何内容。

我无法解决此错误。任何帮助,将不胜感激。 感谢

1 个答案:

答案 0 :(得分:1)

您正尝试在测试之外访问数据库。这是被禁止的。不是在测试之前尝试获取数据并将其作为参数传递,而是在测试中进行。这也可以避免MinSpecSetFamily result = minRT.specList .parallelStream() .flatMap(spec -> getMinimalConstSpecTreeRootedAt(spec).getLeaves().stream()) .map(leaf -> new SpecSet(leaf.getAncestors())) .collect(MinSpecSetFamily::new,MinSpecSetFamily::addSpecSet,MinSpecSetFamily::add); 标记中的代码重复。

parametrize