def test_always_calls_with_quantity(self): with patch("test.generic.tests.test_recipes.choice") as choice_mock: choice.return_value = "foo" l = ["foo", "bar", "spam", "eggs"] r = Recipe(DummyBlankFieldsModel, blank_char_field=lambda: choice(l)) r.make(_quantity=3) self.assertEqual(choice_mock.call_count, 3)
class AddressResponseTests(TestCase): def setUp(self): self.recipe = Recipe( FormFieldResponse, form_field__kind='address', form_field__details={'required': True} ) def test_should_pass_when_required_and_only_addr2_blank(self): field_response = self.recipe.prepare(details={ 'addressLine1': 'x', 'city': 'x', 'state': 'x', 'zip': 'x' }) self.assertEqual(field_response.clean(), None) def test_should_not_pass_when_required_and_any_field_but_addr2_blank(self): field_response = self.recipe.prepare(details={ 'addressLine1': '', 'city': 'x', 'state': 'x', 'zip': 'x' }) self.assertRaises(ValidationError, field_response.clean) def test_should_pass_when_not_required_and_all_fields_blank(self): field_response = self.recipe.prepare() field_response.form_field.details['required'] = False self.assertEqual(field_response.clean(), None)
class LongAnswerResponseTests(TestCase): def setUp(self): self.recipe = Recipe( FormFieldResponse, form_field__kind='long-answer', form_field__details={'required': True} ) def test_should_pass_when_required_and_answer_not_blank(self): field_response = self.recipe.prepare(details={'answer': 'ok'}) self.assertEqual(field_response.clean(), None) def test_should_not_pass_when_required_and_answer_not_provided(self): field_response = self.recipe.prepare(details={}) self.assertRaises(ValidationError, field_response.clean) def test_should_not_pass_when_required_and_answer_blank(self): field_response = self.recipe.prepare(details={'answer': ''}) self.assertRaises(ValidationError, field_response.clean) def test_should_pass_when_not_required_and_answer_not_provided(self): field_response = self.recipe.prepare(details={}) field_response.form_field.details['required'] = False self.assertEqual(field_response.clean(), None) def test_should_pass_when_not_required_and_answer_blank(self): field_response = self.recipe.prepare(details={'answer': ''}) field_response.form_field.details['required'] = False self.assertEqual(field_response.clean(), None)
def test_defining_recipes_str(self): from model_mommy.recipe import seq p = Recipe("generic.Person", name=seq("foo")) try: p.make(_quantity=5) except AttributeError as e: self.fail("%s" % e)
def test_always_calls_with_quantity(self): with patch('test.generic.tests.test_recipes.choice') as choice_mock: choice.return_value = 'foo' l = ['foo', 'bar', 'spam', 'eggs'] r = Recipe(DummyBlankFieldsModel, blank_char_field=lambda: choice(l)) r.make(_quantity=3) self.assertEqual(choice_mock.call_count, 3)
def test_always_calls_when_creating(self): with patch('test.generic.tests.test_recipes.choice') as choice_mock: l = ['foo', 'bar', 'spam', 'eggs'] r = Recipe(DummyBlankFieldsModel, blank_char_field=lambda: choice(l)) r.make().blank_char_field r.make().blank_char_field self.assertEqual(choice_mock.call_count, 2)
def leg_setup(self): self.survey_recipe = Recipe(models.Commutersurvey) self.all_modes = models.Mode.objects.all() self.leg_recipe = Recipe( models.Leg, checkin = self.survey_recipe.make(), mode = cycle(self.all_modes) )
def setUp(self): last_hour = datetime.now() - timedelta(hours=1) # Next hour has 1 minute more because the delay between # the creation of the event and the test execution next_hour = datetime.now() + timedelta(minutes=61) self.event_last_hour = Recipe(Event, ends=last_hour, published=True) self.event_next_hour = Recipe(Event, ends=next_hour, published=True) self.event_unpublished = Recipe(Event, ends=next_hour, published=False)
def test_always_calls_with_quantity(self): with patch('test.generic.tests.test_recipes.choice') as choice_mock: l = ['foo', 'bar', 'spam', 'eggs'] r = Recipe(DummyBlankFieldsModel, blank_char_field = lambda: choice(l) ) r.make(_quantity=3) self.assertEqual(choice_mock.call_count, 3)
class JobSkillsTest(TestCase): def setUp(self): self.skill = Recipe(Skill).make() def test_if_str_rep_is_ok(self): self.assertEqual(self.skill.__str__(), self.skill.name) def test_if_repr_rep_is_ok(self): self.assertEqual(self.skill.__repr__(), self.skill.name)
def test_prepare_recipe_with_foreign_key(self): person_recipe = Recipe(Person, name='John Doe') dog_recipe = Recipe(Dog, owner=foreign_key(person_recipe), ) dog = dog_recipe.prepare() self.assertIsNone(dog.id) self.assertIsNone(dog.owner.id)
def test_defining_recipes_str(self): from model_mommy.recipe import seq p = Recipe('generic.Person', name=seq('foo') ) try: p.make(_quantity=5) except AttributeError as e: self.fail('%s' %e)
def test_always_calls_when_creating(self): with patch('tests.test_recipes.choice') as choice_mock: choice_mock.return_value = 'foo' lst = ['foo', 'bar', 'spam', 'eggs'] r = Recipe(DummyBlankFieldsModel, blank_char_field=lambda: choice_mock(lst)) r.make().blank_char_field r.make().blank_char_field assert choice_mock.call_count == 2
def test_defining_recipes_str(self): from model_mommy.recipe import seq p = Recipe('generic.Person', name=seq('foo') ) try: p.make(_quantity=5) except AttributeError, e: self.fail('%s' %e)
class TestGerarXmlVivaReal: pytestmark = pytest.mark.django_db def setup_method(self, test_method): self.apartamento = Recipe( ImovelVivaReal, tipo_imovel=ImovelVivaReal.TIPO_IMOVEL.apartamento, ) self.casa = Recipe( ImovelVivaReal, tipo_imovel=ImovelVivaReal.TIPO_IMOVEL.casa, ) def teardown_method(self, test_method): pass def test_tipo_transacao(self): # Dado um imovel para venda imovel = self.apartamento.make( eh_para_venda=True, valor_venda=300000, ) # É esperado For Sale / For Rent ou Sale/Rent no tipo_imovel assert imovel.tipo_transacao == 'For Sale' # Quando para locacao e venda imovel.eh_para_locacao = True assert imovel.tipo_transacao == 'Sale/Rent' # Quando para locacao e venda imovel.eh_para_venda = False assert imovel.tipo_transacao == 'For Rent' def test_destaque(self): # Dado um imovel para venda imovel = self.apartamento.make( eh_para_venda=True, valor_venda=300000, ) assert imovel.destaque == False def test_tipoimovel(self): # Dado um imovel para venda apto = self.apartamento.make( eh_para_venda=True, valor_venda=300000, ) casa = self.casa.make( eh_para_venda=True, valor_venda=300000, ) assert apto.tipo_imovel_vivareal == 'Residential / Apartment' assert casa.tipo_imovel_vivareal == 'Residential / Home'
def setup_method(self, test_method): self.apartamento = Recipe( ImovelVivaReal, tipo_imovel=ImovelVivaReal.TIPO_IMOVEL.apartamento, ) self.casa = Recipe( ImovelVivaReal, tipo_imovel=ImovelVivaReal.TIPO_IMOVEL.casa, )
def test_always_calls_when_creating(self): with patch('test.generic.tests.test_recipes.choice') as choice_mock: choice.return_value = 'foo' l = ['foo', 'bar', 'spam', 'eggs'] r = Recipe(DummyBlankFieldsModel, blank_char_field = lambda: choice(l) ) r.make().blank_char_field r.make().blank_char_field self.assertEqual(choice_mock.call_count, 2)
def test_prepare_recipe_with_foreign_key(self): person_recipe = Recipe(Person, name='John Doe') dog_recipe = Recipe( Dog, owner=foreign_key(person_recipe), ) dog = dog_recipe.prepare() self.assertIsNone(dog.id) self.assertIsNone(dog.owner.id)
def test_only_iterators_not_iteratables_are_iterated(self): """Ensure we only iterate explicit iterators. Consider "iterable" vs "iterator": Something like a string is "iterable", but not an "iterator". We don't want to iterate "iterables", only explicit "iterators". """ r = Recipe(DummyBlankFieldsModel, blank_text_field="not an iterator, so don't iterate!") self.assertEqual(r.make().blank_text_field, "not an iterator, so don't iterate!")
class ClustersRecipes(EjRecipes): stereotype = Recipe( Stereotype, name='Stereotypeone', description='description?', conversation=_foreign_key(ConversationRecipes.conversation), ) stereotype_vote = Recipe(StereotypeVote, author=stereotype.make, choice=Choice.AGREE, comment=_foreign_key(ConversationRecipes.comment))
def test_prepare_recipe_without_all_model_needed_data(self): person_recipe = Recipe(Person, name='John Doe') person = person_recipe.prepare() self.assertEqual('John Doe', person.name) self.assertTrue(person.nickname) self.assertTrue(person.age) self.assertTrue(person.bio) self.assertTrue(person.birthday) self.assertTrue(person.appointment) self.assertTrue(person.blog) self.assertTrue(person.wanted_games_qtd) self.assertFalse(person.id)
def test_prepare_recipe_without_all_model_needed_data(self): person_recipe = Recipe(Person, name='John Doe') person = person_recipe.prepare() assert 'John Doe' == person.name assert person.nickname assert person.age assert person.bio assert person.birthday assert person.appointment assert person.blog assert person.wanted_games_qtd assert not person.id
def test_make_recipe_without_all_model_needed_data(self): person_recipe = Recipe(Person, name="John Doe") person = person_recipe.make() self.assertEqual("John Doe", person.name) self.assertTrue(person.nickname) self.assertTrue(person.age) self.assertTrue(person.bio) self.assertTrue(person.birthday) self.assertTrue(person.appointment) self.assertTrue(person.blog) self.assertTrue(person.wanted_games_qtd) self.assertTrue(person.id)
def test_do_query_lookup_empty_recipes(self): """ It should not attempt to create other object when using query lookup syntax """ dog_recipe = Recipe(Dog) dog = dog_recipe.make(owner__name='James') self.assertEqual(Person.objects.count(), 1) self.assertEqual(dog.owner.name, 'James') dog = dog_recipe.prepare(owner__name='Zezin') self.assertEqual(Person.objects.count(), 1) self.assertEqual(dog.owner.name, 'Zezin')
def setUp(self): self.recipe_attrs = { 'name': 'John Doe', 'nickname': 'joe', 'age': 18, 'bio': 'Someone in the crowd', 'birthday': now().date(), 'appointment': now(), 'blog': 'http://joe.blogspot.com', 'wanted_games_qtd': 4, 'birth_time': now() } self.person_recipe = Recipe(Person, **self.recipe_attrs)
def test_do_query_lookup_empty_recipes(self): """ It should not attempt to create other object when using query lookup syntax """ dog_recipe = Recipe(Dog) dog = dog_recipe.make(owner__name='James') self.assertEqual(Person.objects.count(), 1) self.assertEqual(dog.owner.name, 'James') dog = dog_recipe.prepare(owner__name='Zezin') self.assertEqual(Person.objects.count(), 2) self.assertEqual(dog.owner.name, 'Zezin')
def setUp(self): djconfig.reload_maybe( ) # https://github.com/nitely/django-djconfig/issues/31#issuecomment-451587942 User = get_user_model() self.teacher = Recipe(User, is_staff=True).make( ) # need a teacher or student creation will fail. self.student = mommy.make(User) self.assertion = mommy.make(BadgeAssertion) self.badge = Recipe(Badge, xp=20).make() self.badge_assertion_recipe = Recipe(BadgeAssertion, user=self.student, badge=self.badge)
class PowerRecipes(ConversationRecipes): given_bridge_power = Recipe(GivenBridgePower, **_power_kwargs) given_minority_power = Recipe(GivenMinorityPower, **_power_kwargs) comment_promotion = Recipe( CommentPromotion, comment=foreign_key(recipe.comment), promoter=foreign_key( recipe.author.extend(email="*****@*****.**")), ) @pytest.fixture def data(self, request): data = super().data(request) return data
def aggregate_models(): """Set up data for testing aggregate functions.""" award_uri = [None, None, 'yo'] award_fain = [None, None, '123'] award_piid = ['abc', 'def', None] award_types = ['U', 'B', '05', 'B'] start_dates = [ datetime.date(2016, 7, 13), datetime.date(2017, 1, 1), datetime.date( 2018, 6, 1, ), datetime.date( 2018, 1, 1, ), ] end_dates = [ datetime.date(2018, 12, 31), datetime.date(2020, 1, 1), datetime.date(2050, 7, 14), datetime.date(2050, 7, 14) ] obligated_amts = [1000.01, 2000, None, 4000.02] # create awards award_recipe = Recipe( Award, piid=cycle(award_piid), fain=cycle(award_fain), uri=cycle(award_uri), type=cycle(award_types), period_of_performance_start_date=cycle(start_dates), period_of_performance_current_end_date=cycle(end_dates), total_obligation=cycle(obligated_amts), ) award_recipe.make(_quantity=4) # make each award parent of the next parent = None for award in Award.objects.order_by('period_of_performance_start_date'): award.parent_award = parent award.save() parent = award
def _get_recipes(self): """ Génération des recipes """ recipes = [] if self.recipes_data: for recipe_data in self.recipes_data: attrs = recipe_data.copy() for key, value in attrs.items(): if callable(value): attrs[key] = value() recipes.append(Recipe(model, **attrs)) else: recipes.append(Recipe(model)) return recipes
def setUp(self): self.endereco_base = 'Rua Baronesa, 175' self.cidade_base = 'Rio de Janeiro' self.lat_base = -22.8950148 self.lng_base = -43.3542673 self.imovel = mommy.make(Imovel) self.basic_imovel_recipe = Recipe(Imovel, latitude=None, longitude=None) imoveis_recipe = Recipe(Imovel, endereco=self.endereco_base, cidade=self.cidade_base, latitude=self.lat_base, longitude=self.lng_base, disponivel=cycle([False, True]) ) # Cria 9 imóveis alterando disponíveis e indisponíveis imoveis_recipe.make(_quantity=9)
def setUp(self): djconfig.reload_maybe() # https://github.com/nitely/django-djconfig/issues/31#issuecomment-451587942 User = get_user_model() self.teacher = Recipe(User, is_staff=True).make() # need a teacher or student creation will fail. self.student = mommy.make(User) self.submission = mommy.make(QuestSubmission, quest__name="Test")
def test_contact_signal_is_called(self): with patch("pyjobs.marketing.models.new_contact") as mocked_contact: post_save.connect(mocked_contact, sender=Contact) self.contact = Recipe(Contact).make() self.assertTrue(mocked_contact.called)
class ProfileRecipes(EjRecipes): profile = Recipe(Profile) def get_data(self, request): data = super().get_data(request) profile = self.profile.make(user=data.user) return record(data, profile=profile)
class UserRecipes(EjRecipes): token = Recipe(PasswordResetToken, url="random-data", user=_foreign_key(EjRecipes.user)) def get_data(self, request): data = super().get_data(request) return record(data, token=self.token.make(user=data.user))
def setUp(self): self.client = TenantClient(self.tenant) User = get_user_model() self.semester = mommy.make(Semester) self.teacher = Recipe(User, is_staff=True).make( ) # need a teacher or student creation will fail. self.student = mommy.make(User) self.submission = mommy.make(QuestSubmission, quest__name="Test")
class BoardRecipes(Base): board = Recipe( Board, slug='board-slug', title='Title', description='Description', owner=foreign_key(Base.author), )
def test_helper_send_offer_email_template(self, mocked_send_mail): from pyjobs.marketing.models import Contact, Messages self.offer_email = Recipe(Messages, message_type="offer").make() send_offer_email_template(self.job) self.assertTrue(mocked_send_mail.called)
class EjRecipes(metaclass=FixtureMeta): """ Base recipes for the site """ user = Recipe(User, is_superuser=False, email='*****@*****.**', name='user') author = Recipe(User, is_superuser=False, email='*****@*****.**', name='author') root = Recipe(User, is_superuser=True, email='*****@*****.**', is_staff=True, name='root')
def test_helper_send_feedback_collection_email(self, mocked_send_mail): from pyjobs.marketing.models import Contact, Messages self.feedback_email = Recipe(Messages, message_type="feedback").make() send_feedback_collection_email(self.job) self.assertTrue(mocked_send_mail.called)
def criar_dependencia_recipe_imovel(instance): instance.cidade = Recipe(Cidade, nome='Sao Jose dos Campos') instance.regiao = Recipe(Regiao, nome='Oeste', cidade=foreign_key(instance.cidade)) instance.bairro = Recipe(Bairro, nome='Aquarius', regiao=foreign_key(instance.regiao)) instance.proprietario = Recipe(Proprietario, nome='Roger Waters', fone='12998001002') instance.condominio = Recipe(Condominio, cep='12120000', logradouro='Rua Tubarão Branco', numero='900', bairro=foreign_key(instance.bairro), regiao=foreign_key(instance.regiao), cidade=foreign_key(instance.cidade)) instance.apartamento_base = Recipe( Imovel, proprietario=foreign_key(instance.proprietario), tipo_imovel=Imovel.TIPO_IMOVEL.apartamento, dormitorios=2, cidade=foreign_key(instance.cidade), bairro=foreign_key(instance.bairro), complemento='Apto 14A') instance.casa = Recipe(Imovel, proprietario=foreign_key(instance.proprietario), tipo_imovel=Imovel.TIPO_IMOVEL.casa, dormitorios=3, cidade=foreign_key(instance.cidade), bairro=foreign_key(instance.bairro))
class InfoResponseTests(TestCase): def setUp(self): self.recipe = Recipe(FormFieldResponse, form_field__kind='info') def test_should_never_pass(self): for details in [{}, {'answer': 'no good'}]: field_response = self.recipe.prepare(details=details) self.assertRaises(ValidationError, field_response.clean)
def setUp(self): djconfig.reload_maybe( ) # https://github.com/nitely/django-djconfig/issues/31#issuecomment-451587942 # needed because BadgeAssertions use a default that might not exist yet self.sem = mommy.make('courses.semester', pk=djconfig.config.hs_active_semester) self.teacher = Recipe(User, is_staff=True).make( ) # need a teacher or student creation will fail. self.student = mommy.make(User) self.assertion = mommy.make(BadgeAssertion, semester=self.sem) self.badge = Recipe(Badge, xp=20).make() self.badge_assertion_recipe = Recipe(BadgeAssertion, user=self.student, badge=self.badge, semester=self.sem)
def setUp(self): self.recipe = Recipe( FormFieldResponse, form_field__kind='multiple-choice', form_field__details={ 'choices': [{'label': 'A'}, {'label': 'B'}, {'label': 'C'}], 'required': True } )
def build_property(self, model, intent): prop = Recipe(model, intent=intent, address='Rua Silvester, 123', price=100, conditions='IPTU R$ 45,00', neighborhood=self.neighborhood, city=self.city, obs='Propriedade com piscina e churrasqueira') if model is House or model is Apartment: prop = prop.extend( total_bedroom=4, total_suite=3, total_bathroom=2, total_garage=1, ).make() else: prop = prop.extend(area='120m2').make() return prop
class TestPostModel(TestCase): def setUp(self): self.recipe = Recipe(Post, slug=None) def test_str(self): post = self.recipe.make(title='foobar') self.assertEqual(post.__str__(), 'foobar') def test_get_absolute_url(self): post = self.recipe.make(title='foobar') self.assertEqual(post.get_absolute_url(), '/foobar/') def test_queryset(self): # cria 2 posts self.recipe.make(status=cycle([Post.FINISHED, Post.DRAFT]), _quantity=2) # Aprova os finalizados Post.objects.filter(status=Post.FINISHED).update(approved=True) # cria mais 2 posts para termos finalizados não aprovados self.recipe.make(status=cycle([Post.FINISHED, Post.DRAFT]), _quantity=2) self.assertEqual(Post.objects.finished().count(), 2) self.assertEqual(Post.objects.draft().count(), 2) self.assertEqual(Post.objects.approved().count(), 1) self.assertEqual(Post.objects.live().count(), 1)
class Fixtures: def create_employer(self): emp = models.Employer.objects.create(name="ACME", id=1, nochallenge=True, active2015=True, active2016=True) emp.save() def leg_setup(self): self.survey_recipe = Recipe(models.Commutersurvey) self.all_modes = models.Mode.objects.all() self.leg_recipe = Recipe( models.Leg, checkin = self.survey_recipe.make(), mode = cycle(self.all_modes) ) def generate_leg_set(self, checkin): # generates a set of legs to associate with a given checkin # set is complete in the sense of having 1+ leg per direction/day pair self.leg_recipe.make(day='w', direction='fw', checkin=checkin, _quantity=randint(1,3)) self.leg_recipe.make(day='w', direction='tw', checkin=checkin, _quantity=randint(1,3)) self.leg_recipe.make(day='n', direction='fw', checkin=checkin, _quantity=randint(1,3)) self.leg_recipe.make(day='n', direction='tw', checkin=checkin, _quantity=randint(1,3)) def create_legs(self): self.leg_setup() checkin = self.survey_recipe.make() self.generate_leg_set(checkin) checkin.save() return (self.leg_recipe, checkin)
def setUp(self): self.recipe_attrs = { "name": "John Doe", "nickname": "joe", "age": 18, "bio": "Someone in the crowd", "birthday": now().date(), "appointment": now(), "blog": "http://joe.blogspot.com", "wanted_games_qtd": 4, "birth_time": now(), } self.person_recipe = Recipe(Person, **self.recipe_attrs)
def aggregate_models(): """Set up data for testing aggregate functions.""" award_uri = [None, 'yo', 'yo', 'yo'] award_fain = [None, None, '123'] award_piid = ['abc', 'def', None] award_types = ['U', 'B', '05', 'B'] start_dates = [ datetime.date(2016, 7, 13), datetime.date(2017, 1, 1), datetime.date( 2018, 6, 1, ), datetime.date( 2018, 1, 1, ), ] end_dates = [ datetime.date(2018, 12, 31), datetime.date(2020, 1, 1), datetime.date(2050, 7, 14), datetime.date(2050, 7, 14) ] obligated_amts = [1000.01, 2000, None, 4000.02] # create awards award_recipe = Recipe( Award, piid=cycle(award_piid), fain=cycle(award_fain), uri=cycle(award_uri), type=cycle(award_types), period_of_performance_start_date=cycle(start_dates), period_of_performance_current_end_date=cycle(end_dates), total_obligation=cycle(obligated_amts), ) award_recipe.make(_quantity=4)
def setUp(self): self.recipe_attrs = { 'name': 'John Doe', 'nickname': 'joe', 'age': 18, 'bio': 'Someone in the crowd', 'birthday': now().date(), 'appointment': now(), 'blog': 'http://joe.blogspot.com', 'wanted_games_qtd': 4, 'birth_time': now() } self.person_recipe = Recipe( Person, **self.recipe_attrs )
class SingleChoiceResponseTests(TestCase): def setUp(self): self.recipe = Recipe( FormFieldResponse, form_field__kind='single-choice', form_field__details={ 'choices': [{'label': 'A'}, {'label': 'B'}, {'label': 'C'}], 'required': True } ) def test_should_pass_when_required_and_answer_valid_choice(self): field_response = self.recipe.prepare(details={'answer': 'B'}) self.assertEqual(field_response.clean(), None) def test_should_not_pass_when_required_and_answer_non_choice(self): field_response = self.recipe.prepare(details={'answer': 'X'}) self.assertRaises(ValidationError, field_response.clean) def test_should_not_pass_when_required_and_answer_not_provided(self): field_response = self.recipe.prepare(details={}) self.assertRaises(ValidationError, field_response.clean) def test_should_not_pass_when_required_and_answer_blank(self): field_response = self.recipe.prepare(details={'answer': ''}) self.assertRaises(ValidationError, field_response.clean) def test_should_not_pass_when_not_required_and_answer_non_choice(self): field_response = self.recipe.prepare(details={'answer': 'X'}) field_response.form_field.details['required'] = False self.assertRaises(ValidationError, field_response.clean) def test_should_pass_when_not_required_and_answer_not_provided(self): field_response = self.recipe.prepare(details={}) field_response.form_field.details['required'] = False self.assertEqual(field_response.clean(), None) def test_should_pass_when_not_required_and_answer_blank(self): field_response = self.recipe.prepare(details={'answer': ''}) field_response.form_field.details['required'] = False self.assertEqual(field_response.clean(), None)
class IndexTest(TestCase): def setUp(self): last_hour = datetime.now() - timedelta(hours=1) # Next hour has 1 minute more because the delay between # the creation of the event and the test execution next_hour = datetime.now() + timedelta(minutes=61) self.event_last_hour = Recipe(Event, ends=last_hour, published=True) self.event_next_hour = Recipe(Event, ends=next_hour, published=True) self.event_unpublished = Recipe(Event, ends=next_hour, published=False) def test_index_response(self): response = client.get(reverse('index')) self.assertEqual(response.status_code, 200) def test_index_event_list(self): self.event_last_hour.make(_quantity=1) self.event_next_hour.make(_quantity=1) self.event_unpublished.make(_quantity=1) response = client.get(reverse('index')) self.assertEqual(response.context_data.get('event_list').count(), 1)
def description_updatable_models(): cost_or_pricing_data = daims_maps["cost_or_pricing_data_map"].keys() multiple_or_single_award_i = daims_maps["multiple_or_single_award_i_map"].keys() cost_accounting_standards = daims_maps["cost_accounting_standards_map"].keys() fed_biz_opps = daims_maps["fed_biz_opps_map"].keys() action_type = ["A", "B", "C", "D"] transaction_contract_recipe = Recipe( TransactionFPDS, cost_or_pricing_data=cycle(cost_or_pricing_data), multiple_or_single_award_i=cycle(multiple_or_single_award_i), cost_accounting_standards=cycle(cost_accounting_standards), fed_biz_opps=cycle(fed_biz_opps), transaction__action_type=cycle(action_type) ) transaction_assistance_recipe = Recipe( TransactionFABS, transaction__action_type=cycle(action_type) ) transaction_contract_recipe.make(_quantity=10) transaction_assistance_recipe.make(_quantity=10)
) serial_numbers_by = Recipe(DummyDefaultFieldsModel, default_decimal_field = seq(Decimal('20.1'), increment_by=Decimal('2.4')), default_int_field = seq(10, increment_by=3), default_float_field = seq(1.23, increment_by=1.8) ) serial_datetime = Recipe(DummyDefaultFieldsModel, default_date_field = seq(TEST_TIME.date(), timedelta(days=1)), default_date_time_field = seq(TEST_TIME, timedelta(hours=3)), default_time_field = seq(TEST_TIME.time(), timedelta(seconds=15)) ) dog = Recipe(Dog, breed = 'Pug', owner = foreign_key(person) ) homeless_dog = Recipe(Dog, breed = 'Pug', ) other_dog = Recipe(Dog, breed = 'Basset', owner = foreign_key('person') ) dog_with_friends = dog.extend( friends_with=related(dog, dog), )
class ImovelTest(TestCase): def setUp(self): self.endereco_base = 'Rua Baronesa, 175' self.cidade_base = 'Rio de Janeiro' self.lat_base = -22.8950148 self.lng_base = -43.3542673 self.imovel = mommy.make(Imovel) self.basic_imovel_recipe = Recipe(Imovel, latitude=None, longitude=None) imoveis_recipe = Recipe(Imovel, endereco=self.endereco_base, cidade=self.cidade_base, latitude=self.lat_base, longitude=self.lng_base, disponivel=cycle([False, True]) ) # Cria 9 imóveis alterando disponíveis e indisponíveis imoveis_recipe.make(_quantity=9) def test_get_disponiveis_qtd(self): """Garante que tem 5 imóveis disponíveis apenas""" imoveis = Imovel.get_disponiveis() self.assertEqual(5, len(imoveis)) def test_get_disponiveis_value(self): """Garante que todos os imóveis retornados estão com disponível True""" imoveis = Imovel.get_disponiveis() self.assertEqual([True] * len(imoveis), [i.disponivel for i in imoveis]) def test_get_proximos_a_vazio(self): imoveis = Imovel.get_proximos_a(latitude=0, longitude=0) self.assertEqual(0, len(imoveis)) def test_get_proximos(self): coordenadas = get_coordenates("Rua Baronesa, 300, Rio de Janeiro") imoveis = Imovel.get_proximos_a(latitude=coordenadas[0], longitude=coordenadas[1]) self.assertGreater(len(imoveis), 0) def test_get_proximos_mais_longe(self): coordenadas = get_coordenates("Rua Nelson Cardoso, 300, Rio de Janeiro") imoveis = Imovel.get_proximos_a(latitude=coordenadas[0], longitude=coordenadas[1]) self.assertEquals(len(imoveis), 0) def test_get_proximos_mais_longe_haversine(self): """ Esse endereço fica a 1.2km do endereço que possui imóveis Porém ele fica dentro das coordenadas mínimas e máximas. A validação adicional através da fórmula garante que nenhum resultado será encontrado """ coordenadas = get_coordenates("Rua Luiz Beltrão, 646, Rio de Janeiro") # Garante que o endereço pesquisado está dentro do "quadrado" inicial de filtragem bounds = get_min_max_coordenates(self.lat_base, self.lng_base) self.assertGreaterEqual(coordenadas[0], bounds[0]) self.assertLessEqual(coordenadas[0], bounds[1]) self.assertGreater(coordenadas[1], bounds[2]) self.assertLessEqual(coordenadas[1], bounds[3]) # Procura imóveis na região do endereço, mas graças a fórmula ninguém é encontrado imoveis = Imovel.get_proximos_a(latitude=coordenadas[0], longitude=coordenadas[1]) self.assertEquals(len(imoveis), 0) def test_custom_save_erro(self): imovel = self.basic_imovel_recipe.prepare() with self.assertRaises(IntegrityError): imovel.save() def test_custom_save(self): imovel = self.basic_imovel_recipe.prepare(endereco=self.endereco_base, cidade=self.cidade_base) imovel.save() self.assertIsNotNone(imovel.latitude) self.assertIsNotNone(imovel.longitude) self.assertIsNotNone(imovel.endereco_formatado) def test_remover_anuncio(self): self.imovel.remover_anuncio() self.assertFalse(self.imovel.disponivel) def test_str(self): self.assertTrue('Imóvel em %s' % self.imovel.endereco, str(self.imovel))
def test_accepts_iterators(self): r = Recipe(DummyBlankFieldsModel, blank_char_field=iter(['a', 'b', 'c'])) self.assertEqual('a', r.make().blank_char_field) self.assertEqual('b', r.make().blank_char_field) self.assertEqual('c', r.make().blank_char_field)
def test_empty_iterator_exception(self): r = Recipe(DummyBlankFieldsModel, blank_char_field=iter(['a', 'b'])) self.assertEqual('a', r.make().blank_char_field) self.assertEqual('b', r.make().blank_char_field) self.assertRaises(RecipeIteratorEmpty, r.make)
def test_accepts_callable(self): r = Recipe(DummyBlankFieldsModel, blank_char_field = lambda: 'callable!!' ) value = r.make().blank_char_field self.assertEqual(value, 'callable!!')