gpt4 book ai didi

python - Django 测试模型属性

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:25 25 4
gpt4 key购买 nike

下面是我当前的 coverage.py 报告的屏幕截图。

enter image description here

我不确定如何100% 覆盖此模型。如何测试第 13-20 行?在我的 tests_model.py 中,我假设通过创建一个实例来覆盖它。但事实并非如此。

# Core Django imports
from django.test import TestCase

# Third-party app imports
import nose.tools as noz
from model_mommy import mommy
from model_mommy.recipe import Recipe, foreign_key


# app imports
from ..models.company import Company
from testapp.apps.profiles.models.appUserModel import AppUser

class CompanyModel(TestCase):
def setUp(self):
self.company = mommy.make(Company)
noz.assert_true(isinstance(self.company, Company))


def test_company_user_count_is_0(self):
company = mommy.make(Company)
noz.assert_equal(company.company_user_count(), 0)

def test_company_user_count(self):
# Relationship can be one-to-many with users.
company = mommy.make(Company)
user1, user2 = mommy.make(AppUser, _quantity=2)
company.users.add(user1)
company.users.add(user2)
noz.assert_equal(company.company_user_count(), 2)


def test_company_unicode(self):
noz.assert_equal(self.company.__unicode__(), self.company.name)

我试图在同一个测试文件中测试每个属性自己的属性,例如...

def test_name(self):
company = mommy.make(Company, name="Test Name")
noz.assert_equal(company.name, "Test Name")

但这对我的覆盖率分数没有任何影响。

根据评论我也试过这个:

def test_name(self):
company = mommy.make(Company)
company.name = "Test"
company.save()
noz.assert_equal(company.name, "Test")

但同样,这对分数没有影响。

这些是我的测试设置...

INSTALLED_APPS += (

'django_nose',
'django_coverage',
'django_extensions',

)

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

NOSE_ARGS = [
'--with-coverage',
'--cover-package=testapp.apps.profiles,testapp.apps.referrals',
'--cover-html'

]

控制台输出:

> python manage.py test
.........
Name Stmts Miss Cover Missing
------------------------------------------------------------------------------------------------
testapp.apps.referrals.models 1 1 0% 1
testapp.apps.referrals.models.company 17 15 12% 1-24, 27
------------------------------------------------------------------------------------------------
TOTAL 136 73 46%
----------------------------------------------------------------------

目录:

testapp/
manage.py
testapp/
__init__.py
apps/
__init__.py
referrals/
__init__.py
tests/
__init__.py
model_tests.py

最佳答案

参见 this issue在 django_coverage 项目页面上。

另外,看看 coverage.py official FAQ ,尤其是这个:

Q: Why do the bodies of functions (or classes) show as executed,
but the def lines do not?

似乎覆盖机制是在您的模型实际导入后启动的。

尝试回到标准 Django 测试场景(使​​用内置测试运行器)并通过发出以下命令手动运行覆盖:

coverage run --source='.' ./manage.py test
coverage report
coverage html

查看报告是否不同。

关于python - Django 测试模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com