Django TestCase client.logout() неправильно выводит пользователя из системы
Я пишу несколько тестов для Django. У меня возникли проблемы с методом client.logout(), который, похоже, не выводит тестового клиента из журнала.
Вот мой setUp():
def setUp(self):
# Set up a user to use with all of the tests and log in the user.
User.objects.create_user(username='temporary', password='temporary')
self.client.login(username='temporary', password='temporary')
# Create second user for later use.
User.objects.create_user(username='temporary2', password='temporary2')
А вот мой метод тестирования:
def test_user_can_only_access_own_recipes(self):
"""
A user should only be able to access recipes they have created.
"""
# temporary1 user already logged in via setUp().
user_1_recipe = self.create_recipe()
self.client.logout()
# Login second user and create recipe.
self.client.login(username='temporary2', password='temporary2')
user_2_recipe = self.create_recipe()
# Response_owned is a recipe made by user 2, who is still logged in, so the recipe should
be viewable.
# Response_not_owned is recipe made by user 1 and should not be viewable as they are
logged out.
response_owned = self.client.get(
reverse('recipes:display_recipe', args=(user_2_recipe.id,)))
response_not_owned = self.client.get(
reverse('recipes:display_recipe', args=(user_1_recipe.id,)))
self.assertEqual(response_not_owned.status_code, 403)
# Convert to str, otherwise Django compares 'temporary' with just temporary no quotes.
self.assertEqual(str(user_1_recipe.user), 'temporary')
self.assertEqual(user_2_recipe.user, 'temporary2')
self.assertEqual(response_owned.status_code, 200)
Это не удается с ошибкой утверждения:
self.assertEqual(user_2_recipe.user, 'temporary2')
AssertionError: <User: temporary> != 'temporary2'
Итак, мой тест должен создать рецепт, принадлежащий пользователю 1. Пользователь 1 должен выйти из системы, затем войти пользователь 2, и будет создан рецепт, принадлежащий пользователю 2. Тест должен проверить, может ли второй пользователь получить доступ к своему собственному рецепту и не может получить доступ к рецепту первого пользователя. Проблема в том, что, похоже, вошел только первый пользователь, поскольку ошибка утверждения гласит, что второй рецепт все еще принадлежит первому пользователю. Я не думаю, что logout() вообще выводит из системы первого пользователя. Любая помощь в этом вопросе была бы очень признательна.
РЕДАКТИРОВАНИЕ:
Посмотрите метод create_recipe() ниже. После комментариев Iain Shelvington стало ясно, что я добавлял одного и того же пользователя 'temporary' в каждый рецепт, созданный методом create_recipe, включив эту строку:
user = User.objects.get(username='temporary'),
Измененный метод, принимающий имя пользователя в качестве аргумента, выглядит следующим образом, и тест теперь может быть изменен, чтобы позволить сообщению быть от любого пользователя, который вам нравится.
def create_recipe(self, recipe_name='Test Recipe', username='temporary'):
"""
Creates a recipe with default values and a modifiable name to be
used in tests.
"""
recipe = RecipeCard.objects.create(
user = User.objects.get(username=username),
# REMAINDER OF CODE
ОРИГИНАЛЬНЫЙ КОД:
def create_recipe(self, recipe_name='Test Recipe'):
"""
Creates a recipe with default values and a modifiable name to be
used in tests.
"""
# Object is receiving default values that can be changed when method
# is used
recipe = RecipeCard.objects.create(
user = User.objects.get(username='temporary'),
recipe_name=recipe_name,
source = 'Test Source',
servings = 3,
active_time_hours = 2,
active_time_minutes = 15,
total_time_hours = 2,
total_time_minutes = 15,
recipe_description = 'Test Description')
recipe.save()
ingredient = Ingredient.objects.create(
ingredient_name = 'Test Ingredient',
quantity = 1,
recipe = recipe)
ingredient.save()
method = MethodStep.objects.create(
step = 'Test Step',
recipe = recipe)
method.save()
# Make sure you return the created recipe object for use when method
# is called in tests.
return recipe