def test_places_main_returns_last_place_if_there_is_no_chosen(self): """ If there is no 'chosen=True' places in the city it should return last 'place' in the city. """ city = CityFactory() mentor = UserFactory( profile__role=Profile.Role.MENTOR, profile__city=city, ) PlaceFactory.create_batch( # previous not chosen places 10, city=city, published=True, chosen=False, ) last_not_chosen_place = PlaceFactory( city=city, published=True, chosen=False, ) client = APIClient() client.force_authenticate(user=mentor) response_data = client.get(PLACES_MAIN).data place_id = response_data.get("id") self.assertEqual( place_id, last_not_chosen_place.id, msg=("Если нет места с 'chosen=True' должно возвращаться" "последнее."), )
def test_unique_place_for_city_constraint(self): city = CityFactory() address = "Абонентский ящик АЯ 23" title = "Место 1" PlaceFactory(city=city, address=address, title=title) with self.assertRaises( IntegrityError, msg=("Убедитесь, что нельзя создать место с одним названием, " "адресом и городом."), ): PlaceFactory(city=city, address=address, title=title)
def test_duplicate_place_for_city_cannot_be_created(self): """Error should return when try to post existed place.""" existed_place = PlaceFactory() client = ViewPlacesTests.authorized_client data = { "activity_type": 1, "address": existed_place.address, "age": 25, "city": existed_place.city.id, "image_url": get_temporary_image(), "title": existed_place.address, } response = client.post( path=PLACES, data=data, format="multipart", ) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST, msg=("Проверьте, что при попытке создать событие с одинаковым " "адресом, названием и городом возвращается ошибка 400."), )
def setUpClass(cls) -> None: super().setUpClass() cls.city = CityFactory(name="Тула") cls.mentor = UserFactory( profile__role=Profile.Role.MENTOR, profile__city=cls.city, ) PlaceFactory.create_batch( 10, city=cls.city, published=True, ) cls.unauthorized_client = APIClient() cls.authorized_client = APIClient() cls.authorized_client.force_authenticate(user=cls.mentor)
def test_places_main_returns_last_place_with_chosen_true(self): """Should return last place with 'chosen=True'.""" chosen_place = PlaceFactory(city=ViewPlacesTests.city, published=True, chosen=True) PlaceFactory( # not chosen place city=ViewPlacesTests.city, published=True, chosen=False) client = ViewPlacesTests.authorized_client response_data = client.get(PLACES_MAIN).data place_id = response_data.get("id") self.assertEqual( place_id, chosen_place.id, msg=("В main должен возвращаться последний опубликованный" "объект с атрибутом 'chosen=True'"), )
def test_authorized_user_chosen_is_false_filter(self): """Result should have only places with 'chosen=False' field.""" PlaceFactory.create_batch( 10, city=FilterTests.mentor.profile.city, published=True, chosen=False, ) client = FilterTests.authorized_client query_param = {"chosen": False} response_data = client.get(PLACES_URL, query_param).data count = response_data.get("count") self.assertEqual( count, 10, msg=("Фильтр 'chosen=False' должен отдавать только места с этим" "флагом."), )
def test_places_tag_field_correct(self): client = ViewPlacesTests.authorized_client tag = PlacesTagFactory(name="test", slug="test") PlaceFactory( published=True, tags=[tag], city=ViewPlacesTests.city, ) response_data = client.get(PLACES).data results = response_data.get("results")[0]["tags"][0]["name"] self.assertTrue(str(tag) in results)
def test_places_main_returns_last_chosen_place_in_city(self): """Should return last place with 'chosen=True' in the city.""" other_city = CityFactory() place_in_city = PlaceFactory( city=ViewPlacesTests.city, published=True, chosen=True, ) PlaceFactory( # place in other city city=other_city, published=True, chosen=True, ) client = ViewPlacesTests.authorized_client response_data = client.get(PLACES_MAIN).data place_id = response_data.get("id") self.assertEqual( place_id, place_in_city.id, msg="В main должен возвращаться последний объект в городе.", )
def test_places_main_returns_last_place(self): """ Should return last published place with 'chosen=True' in the city. """ PlaceFactory( # previous_place city=ViewPlacesTests.city, published=True, chosen=True, ) last_place = PlaceFactory(city=ViewPlacesTests.city, published=True, chosen=True) client = ViewPlacesTests.authorized_client response_data = client.get(PLACES_MAIN).data place_id = response_data.get("id") self.assertEqual( place_id, last_place.id, msg=("В main должен возвращаться последний опубликованный" "объект. Не предыдущий."), )
def test_places_list_ordering(self): """Last created place should be first.""" mentor = ViewPlacesTests.mentor last_place = PlaceFactory( city=mentor.profile.city, published=True, ) client = ViewPlacesTests.authorized_client response_data = client.get(PLACES).data result = response_data.get("results")[0] self.assertEqual( result["id"], last_place.pk, msg="Последнее опубликованное место должно быть первым в списке.", )
def test_places_info_filed_non_gender(self): """Comparing 'info' field in place without gender.""" mentor = ViewPlacesTests.mentor PlaceFactory( city=mentor.profile.city, gender=None, age=10, activity_type=1, published=True, ) expected_info = "10 лет. Развлекательный отдых" client = ViewPlacesTests.authorized_client response_data = client.get(PLACES).data result = response_data["results"][0] self.assertEqual( result["info"], expected_info, msg=("Когда не задан пол, информация о месте должна выглядеть" "как в примере."), )
def test_places_info_filed_male_gender(self): """Comparing 'info' field in place with Male gender.""" mentor = ViewPlacesTests.mentor PlaceFactory( city=mentor.profile.city, gender="M", age=16, activity_type=0, published=True, ) expected_info = "Мальчик, 16 лет. Активный отдых" client = ViewPlacesTests.authorized_client response_data = client.get(PLACES).data result = response_data["results"][0] self.assertEqual( result["info"], expected_info, msg=("Когда у места задан пол ребенка, информация должна выглядеть" "как в примере."), )
def test_unpublished_place_should_not_be_listed(self): """ Unpublished places should not be counted. It counts places in city, after it creates once more unpublished place and counts againg. The amount should be the same. """ client = FilterTests.authorized_client response_data = client.get(PLACES_URL).data places_amount_before_creating = response_data.get("count") PlaceFactory( city=FilterTests.mentor.profile.city, published=False, ) response_data = client.get(PLACES_URL).data places_amount_after_creating = response_data.get("count") self.assertEqual( places_amount_before_creating, places_amount_after_creating, msg="Неопубликованные места должны отсутствовать в списке.", )
def setUpClass(cls) -> None: super().setUpClass() cls.city = CityFactory() cls.other_city = CityFactory() cls.mentor = UserFactory(profile__city=cls.city) cls.tag_1 = PlacesTagFactory(name="tag1") cls.tag_2 = PlacesTagFactory(name="tag2") PlaceFactory.create_batch( 10, tags=[cls.tag_1], city=cls.city, published=True, chosen=True, ) PlaceFactory.create_batch( 20, tags=[cls.tag_2], city=cls.other_city, published=True, chosen=True, ) PlaceFactory.create_batch( 40, tags=[cls.tag_2], city=cls.city, published=True, chosen=True, ) cls.unauthorized_client = APIClient() cls.authorized_client = APIClient() cls.authorized_client.force_authenticate(user=cls.mentor)
def setUpClass(cls) -> None: super().setUpClass() cls.city = CityFactory(name="Учтюпинск") cls.tag = PlacesTagFactory(name="test") cls.place = PlaceFactory(tags=[cls.tag])
def create_place(self, arg): for _ in range(arg): num_tags = random.randint(1, 5) PlaceFactory.create(tags__num=num_tags)
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." ) )