我已经完成了Django民意调查教程,我希望通过进行测试来检查投票竞争状况here。我发现了一个名为before_after的python包,它可用于进行涉及竞争条件的测试。但是,我不了解before
和after
方法的参数。我已查看some examples并认为Choice.get_votes
是我的第一个参数所需要的,但这会导致我获得ImportError: No module named 'Choice'
。有谁知道我需要在我的测试中改变它才能使它工作?
这是我做的测试:
tests.py:
import datetime
from django.utils import timezone
from django.test import TestCase
from .models import Question, Choice
import before_after
def create_question(question_text, days):
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
class ChoiceTest(TestCase):
def test_race_condition_avoided(self):
self.assertEqual(self.creating_race_condition(), 2, "Votes do not equal amount expected.")
def test_race_condition_occurred(self):
self.assertNotEqual(self.creating_race_condition(), 1, "Votes do equal amount expected from a race condition.")
def creating_race_condition(self):
q = create_question('Did the race condition happen?', 0)
self.choice = q.choice_set.create(choice_text="Let's find out.", votes=0)
with before_after.after('Choice.get_votes', self.increment_vote):
self.increment_vote()
return c.votes
def increment_vote(self):
self.choice.votes += 1
self.choice.save()
def get_votes(self):
return self.choice.votes
models.py:
import datetime
from django.utils import timezone
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
我正在使用Python 3.5.1&amp; Django 1.10.4
答案 0 :(得分:0)
before_after
需要您使用完整路径来导入函数。
您需要使用'vote.models.Choice.get_votes'
之类的str来为其提供完整的导入路径。