Djagno login_required单元测试

时间:2017-09-04 06:26:16

标签: python django python-unittest django-testing django-unittest

我遇到模板测试问题。一切都运行良好,直到我添加了login_required装饰器。现在,当我在模板使用测试期间测试状态代码和模板加载错误时,我收到一个断言错误。我尝试了很多东西(创建超级用户,is_active = True等等),但没有结果。我做错了什么?

P.S 包含Django's self.client.login(...) does not work in unit tests的所有解决方案都不起作用。

test.py

class CityViewTests(TestCase):
    def setUp(self):
        user = User.objects.create_user(username='test_username', 
password='12345', email='random@wp.pl')

def test_call_view_loads(self):
        self.client.login(username='test_username', password='12345')
        response = self.client.get('main_view')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'main_view.html')

url.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^main_view/$', views.main_view, name='main_view'),
    url(r'^turn_calculations/$', views.turn_calculations, 
name='turn_calculations')
]

views.py

@login_required
def main_view(request):
    user = User.objects.get(id=request.user.id)
    city_id = City.objects.get(user_id=user.id).id
    city = City.objects.get(id=city_id)
    profile = Profile.objects.get(user_id=request.user.id)
    population = Citizen.objects.filter(city_id=city_id).count()
    income = 
Citizen.objects.filter(city_id=city_id).aggregate(Sum('income'))
['income__sum']
max_population = Residential.objects.filter(city_id=city_id).aggregate(Sum('max_population'
))['max_population__sum']
    house_number = Residential.objects.filter(city_id=city_id).count()
    return render(request, 'main_view.html', {'city': city,
                                              'profile': profile,
                                              'population': 
population,
                                              'max_population': 
max_population,
                                              'house_number': 
house_number,
                                              'income': income})

0 个答案:

没有答案