我使用coverage来测试views.py中的这个视图:
class Login(View):
template_name = ['cost_control_app/login.html', 'cost_control_app/home.html']
def get(self, request, *args, **kwargs):
form = UsersForm()
return render(request, self.template_name[0],{"form":form,})
def post(self, request, *args, **kwargs):
#import pdb; pdb.set_trace()
username = request.POST['username']
password = request.POST['password']
#import pdb; pdb.set_trace()
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
if user.is_active:
form_group = GroupsForm()
lista = definetree(request.user.groups.all()[0].name, request.user.id)
return render_to_response(self.template_name[1], {"form_group" : form_group,
"groups":lista[0],
"subgroups":lista[1] ,
"sub_subgroups":lista[2],
"cost_items":lista[3],
"count_requests":lista[4],
},RequestContext(request))
else:
logout_view(request)
else:
return HttpResponseRedirect(reverse('cost_control_app:login'))
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('cost_control_app:login'))
这是我对test_views.py中的视图的测试:
class test_login_out(TestCase):
fixtures = ['test_data_cost_control_app.json']
def test_login_get(self):
request = HttpRequest()
request.method = 'GET'
Login.as_view()(request)
def test_login_post(self):
request = HttpRequest()
request.method = 'POST'
#import pdb; pdb.set_trace()
tuser = User.objects.create_user(
username='jsanchesan', email='jacob@test.com', password='abcd1234')
search = User.objects.get(username = tuser.username)
search.is_active = False
search.save()
request.POST['username'] = search.username
request.POST['password'] = 'abcd1234'
engine = import_module(settings.SESSION_ENGINE)
session_key = None
request.session = engine.SessionStore(session_key)
Login.as_view()(request)
在调用logout_view(request)函数之前一直顺利,因为抛出了这个错误:
- > logout_view(request)(Pdb)n KeyError:'SERVER_NAME'
知道为什么吗?,提前谢谢。