def test_defining_recipes_str(self): from model_bakery.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_scramble_v3_counts_command(self): from django.db.models import Q, F from model_bakery.recipe import Recipe from random import randint group_aggregate_recipe = Recipe(GroupAggregate, count=randint(0, 1000), count_scrambled=None) group_aggregate_recipe.make(_quantity=100) for ga in GroupAggregate.objects.all(): self.assertIsNotNone(ga.count) self.assertIsNone(ga.count_scrambled) # Do the scrambling call_man_command('scramble_v3_counts') differ_count = 0 for ga in GroupAggregate.objects.all(): self.assertIsNotNone(ga.count_scrambled) self.assertIn(ga.count_scrambled, (ga.count - 1, ga.count, ga.count + 1)) if ga.count_scrambled != ga.count: differ_count += 1 # check all records have their scrambled counts set assert not GroupAggregate.objects.filter(count_scrambled=None).exists() # check that all scrambled counts are within valid range assert not GroupAggregate.objects.filter( Q(count_scrambled__gt=F('count') + 1) | Q(count_scrambled__lt=F('count') - 1)) # Make sure that a significant amount of counts_scrambled were actually changed from the original self.assertGreater(differ_count, 50)
def test_always_calls_with_quantity(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(_quantity=3) assert choice_mock.call_count == 3
def test_defining_recipes_str(self): from model_bakery.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('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(_quantity=3) assert choice_mock.call_count == 3
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() assert dog.id is None assert dog.owner.id is None
def test_do_query_lookup_empty_recipes(self): """It should not create another object when using query lookup syntax.""" dog_recipe = Recipe(Dog) dog = dog_recipe.make(owner__name="James") assert Person.objects.count() == 1 assert dog.owner.name == "James" dog = dog_recipe.prepare(owner__name="Zezin") assert Person.objects.count() == 1 assert dog.owner.name == "Zezin"
def test_scramble_v2_counts_command(self): count_aggregate_recipe = Recipe( CountAggregate, count_in=randint(0, 1000), count_out=randint(0, 1000), count=randint(0, 1000), count_in_scrambled=None, count_out_scrambled=None, count_scrambled=None, ) count_aggregate_recipe.make(_quantity=100) # Do the scrambling call_man_command('scramble_v2_counts') differ_count_in = 0 differ_count_out = 0 differ_count = 0 for ca in CountAggregate.objects.all(): assert ca.count_in_scrambled is not None assert ca.count_in_scrambled in (ca.count_in - 1, ca.count_in, ca.count_in + 1) if ca.count_in_scrambled != ca.count_in: differ_count_in += 1 assert ca.count_out_scrambled is not None assert ca.count_out_scrambled in (ca.count_out - 1, ca.count_out, ca.count_out + 1) if ca.count_out_scrambled != ca.count_out: differ_count_out += 1 assert ca.count_scrambled is not None assert ca.count_scrambled in (ca.count - 1, ca.count, ca.count + 1) if ca.count_scrambled != ca.count: differ_count += 1 # check all records have their scrambled counts set assert not CountAggregate.objects.filter( Q(count_in_scrambled=None) | Q(count_out_scrambled=None) | Q(count_scrambled=None)).exists() # check that all scrambled counts are within valid range assert not CountAggregate.objects.filter( Q(count_in_scrambled__gt=F('count_in') + 1) | Q(count_in_scrambled__lt=F('count_in') - 1), Q(count_out_scrambled__gt=F('count_out') + 1) | Q(count_out_scrambled__lt=F('count_out') - 1), Q(count_scrambled__gt=F('count') + 1) | Q(count_scrambled__lt=F('count') - 1), ) # Make sure that a significant amount of counts_scrambled were actually changed from the original assert differ_count_in > 50 assert differ_count_out > 50 assert differ_count > 50
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.days_since_last_login 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() 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 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_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!") assert r.make( ).blank_text_field == "not an iterator, so don't iterate!"
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') assert Person.objects.count() == 1 assert dog.owner.name == 'James' dog = dog_recipe.prepare(owner__name='Zezin') assert Person.objects.count() == 1 assert dog.owner.name == 'Zezin'
def setUp(self): self.client = TenantClient(self.tenant) self.sem = SiteConfig.get().active_semester self.teacher = Recipe(User, is_staff=True).make( ) # need a teacher or student creation will fail. self.student = baker.make(User) self.assertion = baker.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.client = TenantClient(self.tenant) self.sem = SiteConfig.get().active_semester self.teacher = Recipe(User, is_staff=True).make( ) # need a teacher or student creation will fail. self.student = baker.make(User)
def setUp(self): self.client = TenantClient(self.tenant) User = get_user_model() self.semester = baker.make(Semester) self.teacher = Recipe(User, is_staff=True).make( ) # need a teacher or student creation will fail. self.student = baker.make(User) self.submission = baker.make(QuestSubmission, quest__name="Test")
def setUp(self): op = Recipe(Operacao, houve_ocorrencia_operacao=True, _fill_optional=True).prepare() self.data = { "unidade_responsavel": op.unidade_responsavel, "unidade_apoiadora": op.unidade_apoiadora, "nome_comandante_operacao": op.nome_comandante_operacao, "rg_pm_comandante_operacao": "12345", "posto_comandante_operacao":Operacao.POSTO_COMANDANTE[0][0], }
def setUp(self): self.teacher = Recipe(User, is_staff=True).make() # need a teacher or student creation will fail. self.user = baker.make(User) # Profiles are created automatically with each user, so we only need to access profiles via users self.profile = self.user.profile self.active_sem = SiteConfig.get().active_semester # Why is this required? Why can't I just baker.make(Semester)? For some reason when I # use baker.make(Semester) it tried to duplicate the pk, using pk=1 again?! self.inactive_sem = baker.make(Semester, pk=(SiteConfig.get().active_semester.pk + 1))
def setUp(self): op = Recipe(Operacao, houve_ocorrencia_operacao=True, _fill_optional=True).prepare() self.data = { "boletim_ocorrencia_pm": op.boletim_ocorrencia_pm, "registro_ocorrencia": "034-00001/2019", "nome_condutor_ocorrencia": op.nome_condutor_ocorrencia, "rg_pm_condutor_ocorrencia": "12345", "posto_condutor_ocorrencia": Operacao.POSTO_COMANDANTE[0][0], "houve_apreensao_drogas": op.houve_apreensao_drogas, "numero_armas_apreendidas": op.numero_armas_apreendidas, "numero_fuzis_apreendidos": op.numero_fuzis_apreendidos, "numero_presos": op.numero_presos, }
def test_accepts_generators(self): r = Recipe(DummyBlankFieldsModel, blank_char_field=itertools.cycle(["a", "b"])) assert "a" == r.make().blank_char_field assert "b" == r.make().blank_char_field assert "a" == r.make().blank_char_field
def test_foreign_key_method_returns_a_recipe_foreign_key_object(self): number_recipe = Recipe(DummyNumbersModel, float_field=1.6) obj = foreign_key(number_recipe) assert isinstance(obj, RecipeForeignKey)
def test_accepts_iterators(self): r = Recipe(DummyBlankFieldsModel, blank_char_field=iter(["a", "b", "c"])) assert "a" == r.make().blank_char_field assert "b" == r.make().blank_char_field assert "c" == r.make().blank_char_field
Dog, ) from tests.generic.baker_recipes import SmallDogRecipe, pug recipe_attrs = { "name": "John Doe", "nickname": "joe", "age": 18, "bio": "Someone in the crowd", "birthday": now().date(), "appointment": now(), "blog": "http://joe.blogspot.com", "days_since_last_login": 4, "birth_time": now(), } person_recipe = Recipe(Person, **recipe_attrs) @pytest.mark.django_db class TestDefiningRecipes: def test_import_seq_from_baker(self): """ Import seq method directly from baker module """ try: from model_bakery import seq # NoQA except ImportError: self.fail("{} raised".format(ImportError.__name__)) def test_flat_model_make_recipe_with_the_correct_attributes(self): """
from tests.generic.models import ( TEST_TIME, Person, Dog, DummyDefaultFieldsModel, DummyUniqueIntegerFieldModel, ) from datetime import timedelta person = Recipe( Person, name="John Doe", nickname="joe", age=18, bio="Someone in the crowd", blog="http://joe.blogspot.com", days_since_last_login=4, birthday=now().date(), appointment=now(), birth_time=now(), ) serial_person = Recipe( Person, name=seq("joe"), ) serial_numbers = Recipe( DummyDefaultFieldsModel, default_decimal_field=seq(Decimal("20.1")), default_int_field=seq(10),
from faker import Faker from model_bakery.recipe import Recipe from .models import CauseOfDeath fake = Faker() causeofdeath = Recipe( CauseOfDeath, display_name="cryptococcal_meningitis", name="cryptococcal_meningitis" )
def generate_agent_id(hostname): rand = "".join(random.choice(string.ascii_letters) for _ in range(35)) return f"{rand}-{hostname}" def get_wmi_data(): with open( os.path.join(settings.BASE_DIR, "tacticalrmm/test_data/wmi_python_agent.json")) as f: return json.load(f) agent = Recipe( Agent, hostname="DESKTOP-TEST123", version="1.3.0", monitoring_type=cycle(["workstation", "server"]), salt_id=generate_agent_id("DESKTOP-TEST123"), agent_id="71AHC-AA813-HH1BC-AAHH5-00013|DESKTOP-TEST123", ) server_agent = agent.extend(monitoring_type="server", ) workstation_agent = agent.extend(monitoring_type="workstation", ) online_agent = agent.extend(last_seen=djangotime.now()) overdue_agent = agent.extend(last_seen=djangotime.now() - djangotime.timedelta(minutes=6)) agent_with_services = agent.extend(services=[ {
def test_empty_iterator_exception(self): r = Recipe(DummyBlankFieldsModel, blank_char_field=iter(["a", "b"])) assert "a" == r.make().blank_char_field assert "b" == r.make().blank_char_field with pytest.raises(RecipeIteratorEmpty): r.make()
assessment (Recipe): recipe to create :class:`~makeReports.models.assessment_models.Assessment` model assessmentVersion (Recipe): recipe to create :class:`~makeReports.models.assessment_models.AssessmentVersion` model """ from itertools import cycle from model_bakery.recipe import Recipe, foreign_key from makeReports.models.assessment_models import Assessment, AssessmentVersion from .basic_recipes import report from .slo_recipes import sloInReport titles = [ "Final Paper", "Comprehensive Exam", "Project and Presentation in CSCI 4200", "Capstone Project", "Analytical Paper and Poster", "Team Final Project" ] assessment = Recipe(Assessment, title=cycle(titles)) descriptions = [ "The students will write an analytic paper examining several different cultures.", "The students will prepare a poster outlining a project in statistics. This will be presented to the the board.", "The students will take an exam that draws from all classes they have ever taken.", "The students will write several essays demonstrating rhetorical analysis.", "The students will work as a team to create a project for a client.", "The students will present original research in front of a board. They will be asked questions.", "The students will each create a statistical model.", "The student will perform a series of experiments and write-up the results." ] wheres = [ "During ENGL 4050", "As part of the capstone class", "On a specified day during the last semester",
def test_accepts_callable(self): r = Recipe(DummyBlankFieldsModel, blank_char_field=lambda: "callable!!") value = r.make().blank_char_field assert value == "callable!!"
from model_bakery.recipe import Recipe, foreign_key from multi_tenant import models client = Recipe(models.Client, name="My Great Organization", url="http://vote.local") partnerslug = Recipe(models.PartnerSlug, slug="greatorg", partner=foreign_key(client))