Django rest-framework:单元测试使用的是生产数据库

时间:2018-03-19 15:48:11

标签: django unit-testing django-rest-framework

我目前正在开发一个小应用程序,以了解Django和Django-Rest-Framework,并偶然发现了一个与单元测试相关的小问题。

我的项目中只有两个应用程序:api(提供RESTful api来处理数据库)和web(它只是向api发送查询并应用布局来呈现网页)。没什么复杂的。 但是,在启动单元测试时,那些测试api的工作按预期工作并且似乎使用临时数据库,但那些测试Web应用程序的人似乎使用了生产数据库。

这是我的模型(api.models):

class User(AbstractUser):
    country = models.CharField(max_length=32, verbose_name="Country of origin", name="country", blank=True, null=True)
    phone = models.CharField(max_length=32, verbose_name="Phone", name="phone", blank=True, null=True)
    field = models.CharField(max_length=32, verbose_name="Field of occupation", name="field", blank=True, null=True)
    occupation = models.CharField(max_length=32, verbose_name="Occupation", name="occupation", blank=True, null=True)
    birthdate = models.DateField(verbose_name="Birth Date", name="birthdate", auto_now_add=False, auto_now=False, blank=True, null=True)
    description = models.TextField(verbose_name="Description", name="description", blank=True, null=True)

    def __str__(self):
        return self.username

以下是导致问题的网络视图(web.views):

def profile(request, usrname):
    """Handles profile page behaviour and rendering"""
    stdlogger.info("PROFILE : request for home page")

    if request.method == "GET":
        # retrieve single profile
        stdlogger.debug("PROFILE_get : request for profile of '" + usrname + "' retrieval")
        r = get("http://localhost:8000" + reverse("get_delete_update_profile", kwargs={'usrname': usrname}))
        if r.status_code == status.HTTP_200_OK:
            form = UserForm(data=r.json())

            if not form.is_valid():
                # login data is invalid
                stdlogger.error("PROFILE_get : form data is invalid")
                for field, errors in form.errors.items():
                    for error in errors:
                        stdlogger.error(field + " -> " + error)
                        messages.add_message(request, messages.ERROR, field + " : " + error)

            return render(request, 'web/profile.html', {'form': form, 'usrname': usrname, })
        else:
            stdlogger.error("PROFILE_get : profile for '" + usrname + "' could not be found")
            return HttpResponseNotFound()

这是一个导致问题的单元测试(web.tests.test_views):

from django.test import TestCase, Client

class getProfileTest(TestCase):
"""Test module for GET requests on Profile page"""

    def setUp(self):
        self.client = Client(enforce_csrf_checks=False)
        self.john = get_user_model().objects.create(
        username='john', password='test', first_name='John', last_name='Doe', country='UK', email='test@test.com',
        phone='+44123456789', field='Diplomacy', occupation='Spy', birthdate='1963-05-01', description='Tall guy')

    def test_valid_get_profile(self):
        response = self.client.get(reverse('profile', kwargs={'usrname': self.john.username}))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'web/profile.html')

此测试返回一个Http代码404,当我运行一个记录器时,它会显示生产用户,而不是'John Doe'

有人有任何想法吗? :)

0 个答案:

没有答案