django测试-未创建模型实例

时间:2019-05-09 13:45:06

标签: python django django-testing django-tests model-mommy

我在使用Django和DRF在测试类中为特定模型创建夹具时遇到问题。我正在使用model-mommy,但是即使仅使用该模型的Django ORM创建单个实例也不起作用:

    from rest_framework.test import APIRequestFactory, APITestCase
    from model_mommy import mommy

    from api.v1 import views
    from company.models.models import CompanyUserProfile, ManagerRelation, DynamicRelation


    User = get_user_model()


    class APIViewsTestCase(APITestCase):

        @classmethod
        def setUpTestData(cls):
            supervisory_id = "1337"
            emp_group_id = "119"
            prd_scope_id = "1334"
            user = mommy.make(User)
            setattr(cls, 'user', user)
            company_user_profile_1 = mommy.make(CompanyUserProfile)
            requestor = mommy.make(
                CompanyUserProfile, is_manager=True,
                supervisory_id=supervisory_id, emp_group_id=emp_group_id,
                prd_scope_id=prd_scope_id, user=user
            )
            cls.user = user
            manager_relation = mommy.make(
                ManagerRelation, manager_id=requestor.id, mgr_type="Direct Mgr", _quantity=5
            )
            dynamic_relations = mommy.make(
                DynamicRelation,target_id=requestor.id, _quantity=5
            )

        def setUp(self) -> None:
            super().setUp()
            self.client.force_authenticate(user=self.user)

        def test_employee_view(self):
            CompanyUserProfile.objects.create(
                guid=uuid.uuid4(),
                csod_user_id='idcbijnccdocwocd', csod_username='djchbdcjnwdskjcn',
                id=3333
            )
            print('cup count:', CompanyUserProfile.objects.count())
            print('user count:', User.objects.count())
            print('m_rels count:', ManagerRelation.objects.count())
            print('d_rels count:', DynamicRelation.objects.count())
            rsp = self.client.get('/api/v1/employees/')
            self.assertEqual(rsp.status_code, HTTPStatus.OK)

无论使用CompanyUserProfile还是mommy.make都没有创建CompanyUserProfile.objects.create记录:

-- test run output
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
cup count: 0
user count: 1
m_rels count: 5
d_rels count: 5
Destroying test database for alias 'default'...

CompanyUserProfile继承自AbstractCornerstoneUserProfile(抽象基础模型),这是该模型与其他模型之间的主要区别。

关于这可能是根本原因的任何想法?

1 个答案:

答案 0 :(得分:0)

更新: 解决-> 100%我的错,ModelManager的自定义CompanyUserProfile排除了在CompanyUserProfile.objects.count()上创建的对象。