2

我需要一个允许员工用户查看处于草稿状态的对象的视图。但我发现很难为这个视图编写单元测试。

我正在使用 Factory Boy 进行设置:

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = factory.LazyAttribute(lambda t: random_string())
    password = factory.PostGenerationMethodCall('set_password', 'mysecret')
    email = fuzzy.FuzzyText(
        length=12, suffix='@email.com').fuzz().lower()
    is_staff = True
    is_active = True

class ReleaseFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Release

    headline = factory.LazyAttribute(lambda t: random_string())
    slug = factory.LazyAttribute(lambda t: slugify(t.headline))
    author = factory.LazyAttribute(lambda t: random_string())
    excerpt = factory.LazyAttribute(lambda t: random_string())
    body = factory.LazyAttribute(lambda t: random_string())

class TestReleaseViews(TestCase):
    """
    Ensure our view returns a list of :model:`news.Release` objects.
    """

    def setUp(self):
        self.client = Client()
        self.user = UserFactory.create()
        self.client.login(username=self.user.username, password=self.user.password)

鉴于我现在有一个已登录的员工用户进行测试,我该如何使用它来测试视图(status_code 200 而不是 404)?

例如,当我的视图允许具有is_staffas True 的用户访问视图时,此测试失败 (404 != 200):

def test_staff_can_view_draft_releases(self):
    "ReleaseDetail view should return correct status code"
    release = ReleaseFactory.create(status='draft')
    response = self.client.get(
        reverse(
            'news:release_detail',
            kwargs={
                'year': release.created.strftime('%Y'),
                'month': release.created.strftime('%b').lower(),
                'day': release.created.strftime('%d'),
                'slug': release.slug
            }
        )
    )
    self.assertEqual(response.status_code, 200)
4

2 回答 2

8

404实际上,由于self.client.login调用失败,您会收到错误消息。

当您传递password=self.user.password时,您发送的是密码的哈希值,而不是密码本身。

当你打电话UserFactory()时,你工厂的 factory_boy 采取的步骤是:

  1. 创建一个对象{'username': "<random>", 'is_active': True, 'is_staff': True, 'email': "<fuzzed>@email.com"}
  2. save()
  3. 称呼user.set_password('my_secret')
  4. user.save()再打电话

到那时,user.password是的结果set_password('my_secret')不是'my_secret'

我会去(在你的测试中):

pwd = 'my_super_secret'
self.user = UserFactory(password=pwd)
self.client = Client()
self.assertTrue(self.client.login(username=self.user.username, password=pwd))

顺便说一句,您的电子邮件字段的声明不会像您期望的那样工作:当您编写时factory.fuzzy.FuzzyText(...).fuzz().lower(),这只会在声明类时执行一次UserFactory

您应该改用factory.fuzzy.FuzzyText(chars='abcdefghijklmnopqrstuvwxyz', length=12, suffix='@example.com').

于 2015-04-19T14:56:16.550 回答
0

除了使用客户端之外,我发现实例化视图并直接将请求传递给它很有帮助。

self.request.user = UserFactory()
view = ReleaseView.as_view()
response = view(self.request)

然后你可以

self.assertEqual(response.status_code, desired_status_code)

如果您愿意,甚至可以呈现响应。

于 2015-04-18T17:49:51.697 回答