def test_event_seats_must_more_than_one(self): event = EventFactory(seats=0, ) with self.assertRaisesMessage( expected_exception=ValidationError, expected_message=("Число мест должно быть больше нуля"), ): event.full_clean()
def test_event_startat_cant_be_less_today(self): event = EventFactory(start_at=EventModelTest.past, ) with self.assertRaisesMessage( expected_exception=ValidationError, expected_message=("Проверьте дату начала мероприятия: " "не может быть меньше текущей"), ): event.full_clean()
def test_response_is_paginated(self): """Just look for 'next', 'previous', 'result' keys in response.""" user = ViewAfishaTests.mentor EventFactory.create_batch(50, city=user.profile.city) client = self.return_authorized_user_client(user) response_data = client.get(path=EVENTS_URL).data self.assertTrue("next" in response_data) self.assertTrue("previous" in response_data) self.assertTrue("results" in response_data)
def test_event_endat_cant_be_less_startat(self): event = EventFactory( start_at=EventModelTest.future, end_at=EventModelTest.tomorrow, ) with self.assertRaisesMessage( expected_exception=ValidationError, expected_message=("Проверьте дату окончания мероприятия: " "не может быть меньше даты начала"), ): event.full_clean()
def test_started_but_not_finished_event_appears_in_events_list(self): """Looks for not finished event in /events.""" user = ViewAfishaTests.mentor client_user = self.return_authorized_user_client(user) with freeze_time("2020-01-01"): EventFactory( city=user.profile.city, start_at=datetime(2020, 2, 1, tzinfo=pytz.utc), end_at=datetime(2020, 12, 1, tzinfo=pytz.utc), ) num_events = Event.objects.count() self.assertEqual( num_events, 1, msg="Убедитесь, что тест смог создать событие в прошлом", ) with freeze_time("2020-05-01"): response_data = client_user.get(EVENTS_URL, format="json").data num_events = response_data.get("count") self.assertEqual( num_events, 1, msg=( "Убедитесь, что начавшееся, но не " "закончившееся событие показывается в списке." ), )
def test_finished_events_doesnt_appear_in_events_list(self): """Creates event in past and looked for it today.""" user = ViewAfishaTests.mentor client_user = self.return_authorized_user_client(user) with freeze_time("2010-01-01"): EventFactory( city=user.profile.city, start_at=datetime(2011, 1, 1, tzinfo=pytz.utc), end_at=datetime(2012, 1, 1, tzinfo=pytz.utc), ) num_events = Event.objects.count() self.assertEqual( num_events, 1, msg="Убедитесь, что тест смог создать событие в прошлом", ) response_data = client_user.get(EVENTS_URL, format="json").data num_events = response_data.get("count") self.assertEqual( num_events, 0, msg="Убедитесь, что события в прошедшие события не показываются", )
def test_mentor_cant_book_same_event_twice(self): user = ViewAfishaTests.mentor event = EventFactory( city=user.profile.city, seats=10, ) EventParticipantFactory( user=user, event=event, ) client = self.return_authorized_user_client(user) data = {"event": event.id} response = client.post(path=EVENTS_PATS_URL, data=data, format="json") self.assertContains( response, status_code=400, text="Вы уже зарегистрированы на это мероприятие.", msg_prefix=( f"Проверьте, что пользователь c ролью " f"'{user.profile.role}'не может зарегистрироваться " f"на мероприятие дважды. Вернулось ошибка: " f"{json.loads(response.content)}" ), )
def test_mentor_cant_book_event_with_empty_seats(self): user = ViewAfishaTests.mentor event = EventFactory( city=user.profile.city, seats=40, ) EventParticipantFactory.create_batch( 40, event=event, ) client = self.return_authorized_user_client(user) data = {"event": event.id} response = client.post(path=EVENTS_PATS_URL, data=data, format="json") self.assertContains( response, status_code=400, text="Извините, мест больше нет.", msg_prefix=( f"Проверьте, что пользователь с правами " f"'{user.profile.role}'не может зарегистрироваться " f"на мероприятие на котором закончились места." ), )
def test_mentor_can_book_event(self): """Looks for status code and returned JSON in response""" user = ViewAfishaTests.mentor event = EventFactory( city=user.profile.city, seats=40, ) client = self.return_authorized_user_client(user) data = {"event": event.id} response = client.post(path=EVENTS_PATS_URL, data=data, format="json") self.assertEqual( response.status_code, 201, msg=( "Проверьте, что при успешной регистрации " "возвращается статус 201." ), ) event_participate_record = EventParticipant.objects.get( user=user, event=event ) expected_data = { "id": event_participate_record.id, "event": event.id, } self.assertEqual( response.data, expected_data, msg=("Проверьте, что возвращается правильный JSON."), )
def test_mentor_sees_events_in_the_his_own_city_only(self): """Looks for amount records in responses for different users. user = don't have any records in his city. We expect zero records. users_other_city = has to have 10 records. The test assumes that page size is more than 10 records. """ other_city = CityFactory() user = ViewAfishaTests.mentor user_other_city = UserFactory(profile__city=other_city) EventFactory.create_batch(10, city=other_city) client_user = self.return_authorized_user_client(user) response_data = client_user.get(EVENTS_URL, format="json").data count = response_data.get("count") self.assertEqual( count, 0, msg=( "Убедитесь, что пользователю не возвращаются мероприятия " "в других городах." ), ) client_other_user = self.return_authorized_user_client(user_other_city) response_data = client_other_user.get(EVENTS_URL, format="json").data count = response_data.get("count") self.assertEqual( count, 10, msg=( "Убедитесь, что пользователю показывается мероприятие в его " "городе." ), )
def test_mentor_can_list_available_events_in_his_city(self): """Looks for amount recodes in response. The test assumes that pages size is less or equal 10. """ city = CityFactory(name="Вермонт") other_city = ViewAfishaTests.city user = UserFactory(profile__city=city) client = self.return_authorized_user_client(user) EventFactory.create_batch(10, city=city) EventFactory.create_batch(100, city=other_city) response_data = client.get(path=EVENTS_URL).data results = response_data.get("results") self.assertEqual( len(results), 10, msg=( "Проверьте что пользователь видит все доступные события " "в городе" ), )
def test_mentor_cant_book_event_in_other_city(self): user = ViewAfishaTests.mentor other_city = CityFactory() event = EventFactory( city=other_city, ) client = self.return_authorized_user_client(user) data = {"event": event.id} response = client.post(path=EVENTS_PATS_URL, data=data, format="json") self.assertContains( response, status_code=400, text="Извините, но мероприятие не в Вашем городе.", msg_prefix=( f"Проверьте, что пользователь c ролью " f"'{user.profile.role}'не может зарегистрироваться " f"на мероприятие в другом городе." ), )
def test_mentor_cant_book_event_in_past(self): user = ViewAfishaTests.mentor event = EventFactory( city=user.profile.city, start_at=datetime(2019, 1, 1, tzinfo=pytz.utc), end_at=datetime(2020, 1, 1, tzinfo=pytz.utc), ) client = self.return_authorized_user_client(user) data = {"event": event.id} response = client.post(path=EVENTS_PATS_URL, data=data, format="json") self.assertContains( response, status_code=400, text="Мероприятие уже закончилось.", msg_prefix=( f"Проверьте, что пользователь с правами " f"'{user.profile.role}'не может зарегистрироваться " f"на мероприятие в прошлом." ), )
def test_mentor_can_unbook_event(self): user = ViewAfishaTests.mentor event = EventFactory( city=user.profile.city, ) EventParticipantFactory( user=user, event=event, ) path = reverse("event-participants-detail", args=[event.id]) client = self.return_authorized_user_client(user) response = client.delete( path=path, format="json", ) is_booked = EventParticipant.objects.filter( user=user, event=event, ).exists() self.assertFalse( is_booked, msg=( f"Проверьте, что зарегистрированный пользователь " f"с ролью '{user.profile.role}'" f" может отписаться от мероприятия." ), ) self.assertEqual( response.status_code, 204, msg=( "Проверьте, что при удачной отписке от мероприятия " "возвращается код 204" ), )
def setUpClass(cls): super().setUpClass() cls.city = CityFactory(name="Воркута") cls.mentor = UserFactory( profile__role=Profile.Role.MENTOR, profile__city=cls.city, ) cls.moderator_reg = UserFactory( profile__role=Profile.Role.MODERATOR_REG, profile__city=cls.city, ) cls.moderator_gen = UserFactory( profile__role=Profile.Role.MODERATOR_GEN, profile__city=cls.city, ) cls.admin = UserFactory( profile__role=Profile.Role.ADMIN, profile__city=cls.city, ) cls.users = [ cls.mentor, cls.moderator_reg, cls.moderator_gen, cls.admin, ] cls.event = EventFactory(city=cls.mentor.profile.city, ) cls.booking = EventParticipant.objects.create( user=cls.mentor, event=cls.event, ) cls.unauthorized_client = APIClient() cls.path_events_participants = reverse("event-participants-list") cls.path_individual_booking = reverse( "event-participants-detail", args=[cls.mentor.profile.id], ) cls.path_events = reverse("events")
def test_booked_event_has_true_flag(self): """Looks fot "booked" string in response record.""" user = ViewAfishaTests.mentor event = EventFactory(city=user.profile.city) EventParticipantFactory( event=event, user=user, ) client = self.return_authorized_user_client(user) response_data = client.get(path=EVENTS_URL, format="json").data results = response_data.get("results") record_dict = results[0] self.assertEqual( "True", str(record_dict.get("booked")), msg=( "Проверьте, что у мероприятий на которые " "пользователь подписан возвращается флаг " "booked': True." ), )
def create_event(self, arg): EventFactory.create_batch(arg)
def handle(self, *args, **options): # noqa optional_arguments = 0 for item in list(OPTIONS_AND_FINCTIONS): if options[item]: optional_arguments += 1 with factory.Faker.override_default_locale("ru_RU"): OPTIONS_AND_FINCTIONS[item](options[item][0]) self.stdout.write( self.style.SUCCESS( f"{options[item][0]} {item} created successfully" ) ) if optional_arguments == 0: try: if City.objects.count() > len(CITIES): raise MyException() with factory.Faker.override_default_locale("ru_RU"): for city_name in CITIES: CityFactory(name=city_name) CityFactory.create_batch(10) EventFactory.create_batch(200) CuratorFactory.create_batch(15) RightTagFactory.create_batch(10) for _ in range(70): num_tags = random.randint(1, 5) RightFactory(tags__num=num_tags) for _ in range(70): num_events = random.randint(0, 5) UserFactory(num_events=num_events) QuestionTagFactory.create_batch(15) for _ in range(70): num_tags = random.randint(1, 5) QuestionFactory.create(tags=num_tags) QuestionFactory.create_batch(5) QuestionFactoryWithoutAnswer.create_batch(5) PlacesTagFactory.create_batch(15) for _ in range(70): num_tags = random.randint(1, 5) PlaceFactory.create(tags__num=num_tags) GuideFactory.create_batch(70) MovieTagFactory.create_batch(10) for link in link_movie_list: num_tags = random.randint(1, 5) MovieFactory.create(link=link, tags__num=num_tags) MeetingFactory.create_batch(50) ArticleFactory.create_batch(70) BookTagFactory.create( name="Художественные", slug="hudozhestvennye", color="#C8D1FF", ) BookTagFactory.create( name="Научные", slug="nauchnye", color="#FC8585" ) BookFactory.create_batch(50) VideoTagFactory.create_batch(15) for link in link_video_list: num_tags = random.randint(1, 5) VideoFactory.create(link=link, tags__num=num_tags) StoryFactory.create_batch(30) StoryImageFactory.create_batch(100) MainFactory.create() self.stdout.write( self.style.SUCCESS("The database is filled with test data") ) except MyException: self.stdout.write( self.style.ERROR( "The database is already filled with standard test " "data. To top up individual tables, use the arguments." ) )