正在测试的模型名称未在 Django 中定义错误

modelname being tested is not defined error in Django

我有一个名为 account_engine 的应用,其中有一个名为 CustomerAccount 的模型需要测试。

在models.py

class CustomerAccount(models.Model):

    username = models.EmailField("Email Address")
    date_first_registered = models.DateTimeField()
    last_update = models.DateTimeField(auto_now = True)
    #password = models.TextField()
    password = EncryptedField(max_length=500)

    source = models.CharField(max_length = 10, null = True, blank = True)

    password_reset_token = models.CharField(max_length = 30, null = True, blank = True)


    def __str__(self):
        return u'%s' % (self.id)

    def is_internal_email(self):
        # check if customer account is internal using email domain and set is_internal_email flag accordingly
        self.is_internal_email = False
        internal_emails = ['test.com', 'testing.com', 'testmail.com']
        customer_email = self.username.split('@')[1]
        for email in internal_emails:
            if email == customer_email:
                self.is_internal_email = True
        return self.is_internal_email

在我的 tests.p

import datetime
from django.test import TestCase
from account_engine import models


class CustomerAccountTestCase(TestCase):

    def setUp(self):
        CustomerAccount.objects.create(
            username = 'test@test.com',
            date_first_registered = '2018-05-15 12:32:35.817018',
            password = 'Test@12345'
        )

    def test_get_customeraccount(self):

        first_customer = CustomerAccount.objects.first()
        self.assertEqual(first_customer.username, 'test@test.com')

在运行pythonmanage.py测试中,出现如下错误

======================================================================
ERROR: test_get_customeraccount (account_engine.tests.tests_models.CustomerAccountTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\xxxxxxx\account_engine\tests\tests_models.py", line 9, in setUp
    CustomerAccount.objects.create(
NameError: name 'CustomerAccount' is not defined

----------------------------------------------------------------------

我刚开始学习在 django 中进行测试,所以这可能是一个非常简单的错误。但我无法弄清楚。 另外,我如何测试模型中定义的方法? 另外,一个人应该在模型中测试什么?

它实际上与 Django 本身无关,它是基本的 Python 东西。 Python 的 import 机制与 C 或 PHP 无关,如果你做过 the official Python tutorial:

就会知道

>>> import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions:

>>> fibo.fib(1000)

尝试在不学习 Python 的情况下使用 Django 将是一种痛苦和沮丧的练习,所以真的,花一天时间完成完整的官方教程并浏览文档以了解其中的内容以及在哪里可以找到它,它真的会为您节省很多时间。

Also, how can i test my methods defined in the model ?

错误...调用它们并检查结果?

Also, what all should one test in the model ?

任何非标准的(您自己添加的方法,以及您重写的方法)。您可以放心地假设 Django 按预期工作 - 并不是说​​它完全没有错误(哪个代码是?),但对于大多数部分来说,它确实是经过战场测试的代码,因此您发现基本功能中的错误的机会非常小。