def docker_controller(with_envvars=True, with_labels=True, **kw):
    """
    Generate a DockerController model with (optional) envvars and labels.
    """
    # The slug is used in places where whitespace and colons are problematic,
    # so we remove them from the generated value.
    # TODO: Build a proper SlugField strategy.
    # TODO: Figure out why the field validation isn't being applied.
    # Slugs must be domain-name friendly - used in the "generic" domain
    slug = text(string.ascii_letters + string.digits + '-')
    kw.setdefault("slug", slug)

    kw.setdefault("owner", models(User, is_active=just(True)))
    kw.setdefault("organization", models(Organization, slug=slug))

    # Prevent Hypothesis from generating domains with invalid characters
    domain_urls = text(string.ascii_letters + string.digits + '-.')
    kw.setdefault("domain_urls", domain_urls)

    # The model generator sees `controller_ptr` (from the PolymorphicModel
    # magic) as a mandatory field and objects if we don't provide a value for
    # it.
    controller = models(DockerController, controller_ptr=default_value, **kw)
    if with_envvars:
        controller = controller.flatmap(add_envvars)
    if with_labels:
        controller = controller.flatmap(add_labels)
    return controller
Ejemplo n.º 2
0
class MessageEventTestCase(TestCase):

    @given(random_MessageEvents=st.lists(models(MessageEvent,
                                                username=models(User),
                                                event=models(Event)
                                                )))
    def test_all_MessageEvents_return_name(self, random_MessageEvents):
        for random_MessageEvent in random_MessageEvents:
            self.assertEquals(random_MessageEvent.event.name, str(random_MessageEvent))
Ejemplo n.º 3
0
class EventTestCase(TestCase):

    @given(random_events=st.lists(models(Event)))
    def test_all_events_return_name(self, random_events):
        for random_event in random_events:
            self.assertEquals(random_event.name, str(random_event))

    @given(random_events=st.lists(models(Event)))
    def test_get_absolute_url(self, random_events):
        for random_event in random_events:
            self.assertEquals(random_event.get_absolute_url(), reverse('event-detail', args=[str(random_event.id)]))
Ejemplo n.º 4
0
 def test_foreign_key_primary(self, buf):
     # Regression test for #1307
     company_strategy = models(Company, name=just('test'))
     strategy = models(CompanyExtension,
                       company=company_strategy,
                       self_modifying=just(2))
     try:
         ConjectureData.for_buffer(buf).draw(strategy)
     except HypothesisException as e:
         reject()
     # Draw again with the same buffer. This will cause a duplicate
     # primary key.
     ConjectureData.for_buffer(buf).draw(strategy)
     assert CompanyExtension.objects.all().count() == 1
Ejemplo n.º 5
0
class TestReportHypo(TestCase):
    @given(sampled_from(['csv', 'xlsx', 'ods']),
           lists(
               models(Report,
                      comment=characters(blacklist_categories=['Cc', 'Cs']),
                      task=builds(TaskFactory.create),
                      user=builds(UserFactory.create),
                      date=dates(
                          min_date=date(2000, 1, 1),
                          max_date=date(2100, 1, 1),
                      ),
                      duration=timedeltas(min_delta=timedelta(0),
                                          max_delta=timedelta(days=1))),
               min_size=1,
               max_size=5,
           ))
    @settings(timeout=5, suppress_health_check=[HealthCheck.too_slow])
    def test_report_export(self, file_type, reports):
        get_user_model().objects.create_user(username='******',
                                             password='******')
        client = JSONAPIClient()
        client.login('test', '1234qwer')
        url = reverse('report-export')

        with self.assertNumQueries(4):
            user_res = client.get(url, data={'file_type': file_type})

        assert user_res.status_code == HTTP_200_OK
        book = pyexcel.get_book(file_content=user_res.content,
                                file_type=file_type)
        # bookdict is a dict of tuples(name, content)
        sheet = book.bookdict.popitem()[1]
        assert len(sheet) == len(reports) + 1
def add_labels(controller):
    """
    Generate some MarathonLabel models for the given controller.

    We discard these once we've made them because they're in the database.
    """
    labels = lists(models(MarathonLabel, controller=just(controller)))
    return labels.map(lambda _: controller)
def add_labels(controller):
    """
    Generate some MarathonLabel models for the given controller.

    We discard these once we've made them because they're in the database.
    """
    labels = lists(models(MarathonLabel, controller=just(controller)))
    return labels.map(lambda _: controller)
def add_envvars(controller):
    """
    Generate some EnvVariable models for the given controller.

    We discard these once we've made them because they're in the database.
    """
    envvars = lists(models(EnvVariable, controller=just(controller)))
    return envvars.map(lambda _: controller)
def add_envvars(controller):
    """
    Generate some EnvVariable models for the given controller.

    We discard these once we've made them because they're in the database.
    """
    envvars = lists(models(EnvVariable, controller=just(controller)))
    return envvars.map(lambda _: controller)
Ejemplo n.º 10
0
def rubric_with_questions(min_questions: int=None, max_questions: int=None,
                          average_questions: int=10) -> SearchStrategy:
    def add_questions(rubric: Rubric) -> SearchStrategy:
        return lists(elements=questions(rubric),
                     min_size=min_questions,
                     max_size=max_questions,
                     average_size=average_questions,
                     unique=True).flatmap(lambda _: just(rubric))
    return models(Rubric).flatmap(add_questions)
Ejemplo n.º 11
0
 def test_foreign_key_primary(self, buf):
     # Regression test for #1307
     company_strategy = models(
         Company,
         name=just('test')
     )
     strategy = models(
         CompanyExtension,
         company=company_strategy,
         self_modifying=just(2)
     )
     try:
         ConjectureData.for_buffer(buf).draw(strategy)
     except HypothesisException as e:
         reject()
     # Draw again with the same buffer. This will cause a duplicate
     # primary key.
     ConjectureData.for_buffer(buf).draw(strategy)
     assert CompanyExtension.objects.all().count() == 1
Ejemplo n.º 12
0
class TestGetsBasicModels(TestCase):
    @given(models(Company))
    def test_is_company(self, company):
        self.assertIsInstance(company, Company)
        self.assertIsNotNone(company.pk)

    @given(models(Store, company=models(Company)))
    def test_can_get_a_store(self, store):
        assert store.company.pk

    @given(lists(models(Company)))
    def test_can_get_multiple_models_with_unique_field(self, companies):
        assume(len(companies) > 1)
        for c in companies:
            self.assertIsNotNone(c.pk)
        self.assertEqual(len({c.pk
                              for c in companies}),
                         len({c.name
                              for c in companies}))

    @given(models(Customer))
    def test_is_customer(self, customer):
        self.assertIsInstance(customer, Customer)
        self.assertIsNotNone(customer.pk)
        self.assertIsNotNone(customer.email)

    @given(models(CouldBeCharming))
    def test_is_not_charming(self, not_charming):
        self.assertIsInstance(not_charming, CouldBeCharming)
        self.assertIsNotNone(not_charming.pk)
        self.assertIsNone(not_charming.charm)

    @given(models(SelfLoop))
    def test_sl(self, sl):
        self.assertIsNone(sl.me)

    @given(lists(models(ManyInts)))
    def test_no_overflow_in_integer(self, manyints):
        pass

    @given(models(Customish))
    def test_custom_field(self, x):
        assert x.customish == 'a'

    def test_mandatory_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, models, Store)
Ejemplo n.º 13
0
class TestRestrictedFields(TestCase):
    @given(models(RestrictedFields))
    def test_constructs_valid_instance(self, instance):
        self.assertTrue(isinstance(instance, RestrictedFields))
        instance.full_clean()
        self.assertLessEqual(len(instance.text_field_4), 4)
        self.assertLessEqual(len(instance.char_field_4), 4)
        self.assertIn(instance.choice_field_text, ('foo', 'bar'))
        self.assertIn(instance.choice_field_int, (1, 2))
        self.assertIn(instance.null_choice_field_int, (1, 2, None))
        self.assertEqual(instance.even_number_field % 2, 0)
        self.assertTrue(instance.non_blank_text_field)
Ejemplo n.º 14
0
class TestFieldType(TestCase):
    """A class that randomly select an article object from the data base and
    tests the field types for each parameter
    """
    @settings(suppress_health_check=[
        HealthCheck.filter_too_much, HealthCheck.too_slow
    ])
    @given(models(Article, date=models(Year)), models(Author), models(Label),
           models(Strategies), models(KeyWord))
    def test_with_hypothesis(self, article, author, label, strategy, key_word):

        article.author.add(author)
        article.labels.add(label)
        article.list_strategies.add(strategy)
        article.key_word.add(key_word)

        self.assertTrue(author.article_set.filter(author=author).exists())
        self.assertTrue(label.article_set.filter(labels=label).exists())
        self.assertTrue(
            strategy.article_set.filter(list_strategies=strategy).exists())
        self.assertTrue(
            key_word.article_set.filter(key_word=key_word).exists())

        self.assertEqual(type(article.title), str)
        self.assertEqual(type(article.date.year), int)
        self.assertEqual(type(article.abstract), str)
        self.assertEqual(type(article.key), str)
        self.assertEqual(type(article.pages), str)
        self.assertEqual(type(article.journal), str)
        self.assertEqual(type(article.read), bool)

        self.assertEqual(type(author.name), str)
        self.assertEqual(type(label.label), str)
        self.assertEqual(type(strategy.description), str)
        self.assertLessEqual(len(strategy.strategy_name), 300)
Ejemplo n.º 15
0
    def setUp(self):
        users = [
            models(User).example()
            for _ in range(CommissionApiTest.USERS_NUMBER)
        ]

        test_commissions = [
            models(Commission,
                   date_added=default_value,
                   orderer=just(choice(users)),
                   status=default_value,
                   price=default_value).example()
            for _ in range(CommissionApiTest.COMMISSIONS_NUMBER)
        ]

        CommissionApiTest.AUTH_USER = User.objects.create_user(
            CommissionApiTest.USER_SECRET, '*****@*****.**',
            CommissionApiTest.USER_SECRET)

        CommissionApiTest.OTHER_AUTH_USER = User.objects.create_user(
            CommissionApiTest.OTHER_USER_SECRET, '*****@*****.**',
            CommissionApiTest.OTHER_USER_SECRET)
def docker_controller(with_envvars=True, with_labels=True, **kw):
    """
    Generate a DockerController model with (optional) envvars and labels.
    """
    # The slug is used in places where whitespace and colons are problematic,
    # so we remove them from the generated value.
    # TODO: Build a proper SlugField strategy.
    # TODO: Figure out why the field validation isn't being applied.
    # Slugs must be domain-name friendly - used in the "generic" domain
    slug = text(string.ascii_letters + string.digits + '-')
    kw.setdefault("slug", slug)

    kw.setdefault("owner", models(User, is_active=just(True)))
    kw.setdefault("organization", models(Organization, slug=slug))

    # Prevent Hypothesis from generating domains with invalid characters
    domain_urls = text(string.ascii_letters + string.digits + '-.')
    kw.setdefault("domain_urls", domain_urls)

    # Prevent Hypothesis from generating vhosts with invalid characters
    rabbitmq_vhost_name = text(string.ascii_letters + string.digits + '-.')
    kw.setdefault("rabbitmq_vhost_name", rabbitmq_vhost_name)

    # Prevent Hypothesis from generating usernames with invalid characters
    rabbitmq_vhost_username = text(string.ascii_letters + string.digits + '-.')
    kw.setdefault("rabbitmq_vhost_username", rabbitmq_vhost_username)

    # The model generator sees `controller_ptr` (from the PolymorphicModel
    # magic) as a mandatory field and objects if we don't provide a value for
    # it.
    controller = models(DockerController, controller_ptr=default_value, **kw)
    if with_envvars:
        controller = controller.flatmap(add_envvars)
    if with_labels:
        controller = controller.flatmap(add_labels)
    return controller
Ejemplo n.º 17
0
        },
        "age": {
            "description": "Age",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

EXAMPLE_BAD_SCHEMA1 = "{'why is a string in a dict?'}"
EXAMPLE_BAD_SCHEMA2 = "\"[]\""
EXAMPLE_BAD_SCHEMA3 = "\"af[]23\""


UserGenerator = models(User, username=strategies.text(max_size=30), first_name=strategies.text(
    max_size=30), last_name=strategies.text(max_size=30), email=strategies.just('*****@*****.**'))

SurveyGenerator = models(Survey, schema=strategies.just(
    EXAMPLE_SCHEMA), created_by=UserGenerator)


SurveyGoalData = strategies.fixed_dictionaries(mapping={
    'schema': strategies.one_of(
        strategies.just(EXAMPLE_SCHEMA),
        strategies.text(),
        strategies.just(EXAMPLE_BAD_SCHEMA1),
        strategies.just(EXAMPLE_BAD_SCHEMA2),
        strategies.just(EXAMPLE_BAD_SCHEMA3),
    ),
    'created_by': strategies.integers(),
    'name': strategies.text(),
Ejemplo n.º 18
0
Strategies for generation test objects using Hypothesis (http://hypothesis.works/)
"""

from hypothesis import strategies as st
from hypothesis.extra.django.models import models

from projects.tests.factories import ClaimFactory
from projects.models import Project, Nomination, Claim
from core.tests.factories import ResourceFactory


def generate_with_claims(nomination):
    """
    Magic formula for generating with dependent models.
    cf. http://hypothesis.readthedocs.io/en/latest/django.html#generating-child-models
    """
    return st.lists(
        builds(ClaimFactory,
               nomination=st.just(nomination),
               collection=st.builds(CollectionFactory)),
        min_size=0,
        average_size=2,
    ).map(lambda _: nomination)


nominations = models(
    Nomination,
    project=models(Project),
    resource=st.builds(ResourceFactory),
).flatmap(generate_with_claims)
Ejemplo n.º 19
0
def generate_phone_registration(candidate):
    return models(model=UserRegistration,
                  mobile_number=phone_strategy_clean,
                  candidate=just(candidate))
Ejemplo n.º 20
0
    parsed_number = phonenumbers.parse(number, 'DE')

    assert phonenumbers.is_valid_number_for_region(
        parsed_number, 'de'), parsed_number
    return True

phone_strategy = builds(target=create_mobile_number)
phone_strategy_clean = phone_strategy.filter(lambda x:
                                             valid_mobile_number(x))

candidate_dict = {'model': Candidate,
                  'first_name': name_strategy,
                  'last_name': name_strategy,
                  'date_of_birth': date_strategy}

candidate = models(**candidate_dict)


def generate_email_registration(candidate):
    return models(model=UserRegistration,
                  email=email_strategy,
                  candidate=just(candidate))

candidate_with_email = models(**candidate_dict).flatmap(
    generate_email_registration)


def generate_phone_registration(candidate):
    return models(model=UserRegistration,
                  mobile_number=phone_strategy_clean,
                  candidate=just(candidate))
Ejemplo n.º 21
0
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

# END HEADER

from __future__ import division, print_function, absolute_import

from django.test import TestCase

from hypothesis.strategies import just, lists
from tests.django.toystore.models import Store, Company, Customer
from hypothesis.extra.django.models import models
from hypothesis.extra.django.fixtures import fixture

a_company = fixture(models(Company), lambda c: c.name)

a_different_company = fixture(models(Company), lambda c: len(c.name) > len(a_company().name))

another_company = fixture(models(Company), lambda c: c.name)

some_companies = fixture(lists(models(Company)), lambda ls: len({c.pk for c in ls}) >= 5)


def with_some_stores(company):
    child_strategy = lists(models(Store, company=just(company)), min_size=1)
    return child_strategy.map(lambda _: company)


a_company_with_some_stores = fixture(models(Company).flatmap(with_some_stores), lambda x: x.store_set.count() >= 2)
Ejemplo n.º 22
0
 def test_can_get_examples(self):
     for _ in range(200):
         models(Company).example()
Ejemplo n.º 23
0
class TestGetsBasicModels(TestCase):
    @given(models(Company))
    def test_is_company(self, company):
        self.assertIsInstance(company, Company)
        self.assertIsNotNone(company.pk)

    @given(models(Store, company=models(Company)))
    def test_can_get_a_store(self, store):
        assert store.company.pk

    @given(lists(models(Company)))
    def test_can_get_multiple_models_with_unique_field(self, companies):
        assume(len(companies) > 1)
        for c in companies:
            self.assertIsNotNone(c.pk)
        self.assertEqual(len({c.pk
                              for c in companies}),
                         len({c.name
                              for c in companies}))

    @settings(suppress_health_check=[HealthCheck.too_slow])
    @given(models(Customer))
    def test_is_customer(self, customer):
        self.assertIsInstance(customer, Customer)
        self.assertIsNotNone(customer.pk)
        self.assertIsNotNone(customer.email)

    @settings(suppress_health_check=[HealthCheck.too_slow])
    @given(models(Customer))
    def test_tz_presence(self, customer):
        if django_settings.USE_TZ:
            self.assertIsNotNone(customer.birthday.tzinfo)
        else:
            self.assertIsNone(customer.birthday.tzinfo)

    @given(models(CouldBeCharming))
    def test_is_not_charming(self, not_charming):
        self.assertIsInstance(not_charming, CouldBeCharming)
        self.assertIsNotNone(not_charming.pk)
        self.assertIsNone(not_charming.charm)

    @given(models(SelfLoop))
    def test_sl(self, sl):
        self.assertIsNone(sl.me)

    @given(lists(models(ManyNumerics)))
    def test_no_overflow_in_integer(self, manyints):
        pass

    @given(models(Customish))
    def test_custom_field(self, x):
        assert x.customish == u'a'

    def test_mandatory_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, models, Store)

    def test_mandatory_computed_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, models, MandatoryComputed)

    def test_mandatory_computed_fields_may_not_be_provided(self):
        mc = models(MandatoryComputed, company=models(Company))
        self.assertRaises(RuntimeError, mc.example)

    @given(models(MandatoryComputed, company=default_value))
    def test_mandatory_computed_field_default(self, x):
        assert x.company.name == x.name + u'_company'

    @given(models(CustomishDefault))
    def test_customish_default_generated(self, x):
        assert x.customish == u'a'

    @given(models(CustomishDefault, customish=default_value))
    def test_customish_default_not_generated(self, x):
        assert x.customish == u'b'

    @given(models(OddFields))
    def test_odd_fields(self, x):
        assert isinstance(x.uuid, UUID)
        assert isinstance(x.slug, text_type)
        assert u' ' not in x.slug
        assert isinstance(x.ipv4, str)
        assert len(x.ipv4.split('.')) == 4
        assert all(int(i) in range(256) for i in x.ipv4.split('.'))
        assert isinstance(x.ipv6, text_type)
        assert set(x.ipv6).issubset(set(u'0123456789abcdefABCDEF:.'))

    @given(models(ManyTimes))
    def test_time_fields(self, x):
        assert isinstance(x.time, dt.time)
        assert isinstance(x.date, dt.date)
        assert isinstance(x.duration, dt.timedelta)

    @given(models(Company))
    def test_no_null_in_charfield(self, x):
        # regression test for #1045.  Company just has a convenient CharField.
        assert u'\x00' not in x.name

    @given(binary(min_size=10))
    def test_foreign_key_primary(self, buf):
        # Regression test for #1307
        company_strategy = models(Company, name=just('test'))
        strategy = models(CompanyExtension,
                          company=company_strategy,
                          self_modifying=just(2))
        try:
            ConjectureData.for_buffer(buf).draw(strategy)
        except HypothesisException as e:
            reject()
        # Draw again with the same buffer. This will cause a duplicate
        # primary key.
        ConjectureData.for_buffer(buf).draw(strategy)
        assert CompanyExtension.objects.all().count() == 1
Ejemplo n.º 24
0
import pytest

from django.shortcuts import reverse
from django.contrib.auth.models import User

from hypothesis import given
from hypothesis.extra.django.models import models

from blog.models import Post

HTTP_200_OK = 200


@pytest.mark.django_db
def test_post_ok(client):
    response = client.get(reverse('post-list'))

    assert response.status_code == HTTP_200_OK
    assert response.context_data['view'].__class__.__name__ == 'PostListView'


@given(post=models(Post, author=models(User)))
@pytest.mark.django_db
def test_post_detail_ok(client, post):
    url = reverse('post-detail', kwargs={"slug": post.slug})
    response = client.get(url)

    assert response.status_code == HTTP_200_OK
 def test_mandatory_computed_fields_are_mandatory_old(self):
     with self.assertRaises(InvalidArgument):
         models(MandatoryComputed).example()
Ejemplo n.º 26
0
class TestUser(TestCase):
    @given(models.models(User))
    def test_get_absolute_url(self, user):
        user.get_absolute_url()
Ejemplo n.º 27
0
 def test_mandatory_computed_fields_may_not_be_provided(self):
     mc = models(MandatoryComputed, company=models(Company))
     self.assertRaises(RuntimeError, mc.example)
Ejemplo n.º 28
0
 def test_mandatory_fields_are_mandatory_old(self):
     self.assertRaises(InvalidArgument, models(Store).example)
Ejemplo n.º 29
0
class TestGetsBasicModels(TestCase):

    @given(models(Company))
    def test_is_company(self, company):
        self.assertIsInstance(company, Company)
        self.assertIsNotNone(company.pk)

    @given(models(Store, company=models(Company)))
    def test_can_get_a_store(self, store):
        assert store.company.pk

    @given(lists(models(Company)))
    def test_can_get_multiple_models_with_unique_field(self, companies):
        assume(len(companies) > 1)
        for c in companies:
            self.assertIsNotNone(c.pk)
        self.assertEqual(
            len({c.pk for c in companies}), len({c.name for c in companies})
        )

    @given(models(Customer))
    def test_is_customer(self, customer):
        self.assertIsInstance(customer, Customer)
        self.assertIsNotNone(customer.pk)
        self.assertIsNotNone(customer.email)

    @given(models(CouldBeCharming))
    def test_is_not_charming(self, not_charming):
        self.assertIsInstance(not_charming, CouldBeCharming)
        self.assertIsNotNone(not_charming.pk)
        self.assertIsNone(not_charming.charm)

    @given(models(SelfLoop))
    def test_sl(self, sl):
        self.assertIsNone(sl.me)

    @given(lists(models(ManyInts)))
    def test_no_overflow_in_integer(self, manyints):
        pass

    @given(models(Customish))
    def test_custom_field(self, x):
        assert x.customish == u'a'

    def test_mandatory_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, models, Store)

    def test_mandatory_computed_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, models, MandatoryComputed)

    def test_mandatory_computed_fields_may_not_be_provided(self):
        mc = models(MandatoryComputed, company=models(Company))
        self.assertRaises(RuntimeError, mc.example)

    @given(models(MandatoryComputed, company=default_value))
    def test_mandatory_computed_field_default(self, x):
        assert x.company.name == x.name + u'_company'

    @given(models(CustomishDefault))
    def test_customish_default_generated(self, x):
        assert x.customish == u'a'

    @given(models(CustomishDefault, customish=default_value))
    def test_customish_default_not_generated(self, x):
        assert x.customish == u'b'
Ejemplo n.º 30
0
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import division, print_function, absolute_import

from django.test import TestCase

from hypothesis.strategies import just, lists
from tests.django.toystore.models import Store, Company, Customer
from hypothesis.extra.django.models import models
from hypothesis.extra.django.fixtures import fixture

a_company = fixture(
    models(Company),
    lambda c: c.name,
)

a_different_company = fixture(models(Company),
                              lambda c: len(c.name) > len(a_company().name))

another_company = fixture(
    models(Company),
    lambda c: c.name,
)

some_companies = fixture(lists(models(Company)),
                         lambda ls: len({c.pk
                                         for c in ls}) >= 5)
Ejemplo n.º 31
0
 def test_mandatory_computed_fields_may_not_be_provided(self):
     mc = models(MandatoryComputed, company=models(Company))
     self.assertRaises(RuntimeError, mc.example)
Ejemplo n.º 32
0
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

# END HEADER

from __future__ import division, print_function, absolute_import

from django.test import TestCase
from hypothesis.strategies import just, lists
from tests.django.toystore.models import Store, Company, Customer
from hypothesis.extra.django.models import models
from hypothesis.extra.django.fixtures import fixture

a_company = fixture(
    models(Company),
    lambda c: c.name,
)

a_different_company = fixture(
    models(Company),
    lambda c: len(c.name) > len(a_company().name)
)

another_company = fixture(
    models(Company),
    lambda c: c.name,
)

some_companies = fixture(
    lists(models(Company)),
Ejemplo n.º 33
0
def generate_email_and_phone_registration(candidate):
    return models(model=UserRegistration,
                  email=email_strategy,
                  mobile_number=phone_strategy_clean,
                  candidate=just(candidate))
Ejemplo n.º 34
0
def with_some_stores(company):
    child_strategy = lists(
        models(Store, company=just(company)), min_size=1
    )
    return child_strategy.map(lambda _: company)
Ejemplo n.º 35
0
class TestValidatorInference(TestCase):
    @given(models(User))
    def test_user_issue_1112_regression(self, user):
        assert user.username
Ejemplo n.º 36
0
 def test_mandatory_fields_are_mandatory(self):
     with self.assertRaises(InvalidArgument):
         models(Store)
Ejemplo n.º 37
0
def generate_email_registration(candidate):
    return models(model=UserRegistration,
                  email=email_strategy,
                  candidate=just(candidate))
Ejemplo n.º 38
0
        parsed_number, 'de'), parsed_number
    return True


phone_strategy = builds(create_mobile_number,
                        sampled_from(MOBILE_PHONE_PREFIXES),
                        integers(min_value=1000000, max_value=99999999)).filter(lambda x: x is not None)
phone_strategy_clean = phone_strategy.filter(lambda x:
                                             valid_mobile_number(x))

candidate_dict = {'model': Candidate,
                  'first_name': name_strategy,
                  'last_name': name_strategy,
                  'date_of_birth': date_strategy}

candidate = models(**candidate_dict)


def generate_email_registration(candidate):
    return models(model=UserRegistration,
                  email=email_strategy,
                  candidate=just(candidate))


candidate_with_email = models(**candidate_dict).flatmap(
    generate_email_registration)


def generate_phone_registration(candidate):
    return models(model=UserRegistration,
                  mobile_number=phone_strategy_clean,
Ejemplo n.º 39
0
 def create_question(type_and_weight: tuple) -> SearchStrategy:
     return models(Question,
                   rubric=just(rubric),
                   question_type=just(type_and_weight[0]),
                   weight=just(type_and_weight[1]),
                   short_description=sane_text())
Ejemplo n.º 40
0
def generate_email_registration(candidate):
    return models(model=UserRegistration,
                  email=email_strategy,
                  candidate=just(candidate))
Ejemplo n.º 41
0
 def test_mandatory_computed_fields_are_mandatory_old(self):
     with self.assertRaises(InvalidArgument):
         models(MandatoryComputed).example()
Ejemplo n.º 42
0
def test_creation(db):
    wallet = models(Wallet, user=models(User)).example()
    assert wallet
Ejemplo n.º 43
0
class TestGetsBasicModels(TestCase):
    @checks_deprecated_behaviour
    def test_add_default_field_mapping_is_deprecated(self):
        class UnregisteredCustomishField(CustomishField):
            """Just to get deprecation warning when registered."""

        add_default_field_mapping(UnregisteredCustomishField, just(u"a"))
        with self.assertRaises(InvalidArgument):
            # Double-registering is an error, and registry is shared.
            register_field_strategy(UnregisteredCustomishField, just(u"a"))

    @given(from_model(Company))
    def test_is_company(self, company):
        self.assertIsInstance(company, Company)
        self.assertIsNotNone(company.pk)

    @given(from_model(Store, company=from_model(Company)))
    def test_can_get_a_store(self, store):
        assert store.company.pk

    @given(lists(from_model(Company)))
    def test_can_get_multiple_models_with_unique_field(self, companies):
        assume(len(companies) > 1)
        for c in companies:
            self.assertIsNotNone(c.pk)
        self.assertEqual(
            len({c.pk for c in companies}), len({c.name for c in companies})
        )

    @settings(suppress_health_check=[HealthCheck.too_slow])
    @given(from_model(Customer))
    def test_is_customer(self, customer):
        self.assertIsInstance(customer, Customer)
        self.assertIsNotNone(customer.pk)
        self.assertIsNotNone(customer.email)

    @settings(suppress_health_check=[HealthCheck.too_slow])
    @given(from_model(Customer))
    def test_tz_presence(self, customer):
        if django_settings.USE_TZ:
            self.assertIsNotNone(customer.birthday.tzinfo)
        else:
            self.assertIsNone(customer.birthday.tzinfo)

    @given(from_model(CouldBeCharming))
    def test_is_not_charming(self, not_charming):
        self.assertIsInstance(not_charming, CouldBeCharming)
        self.assertIsNotNone(not_charming.pk)
        self.assertIsNone(not_charming.charm)

    @given(from_model(SelfLoop))
    def test_sl(self, sl):
        self.assertIsNone(sl.me)

    @given(lists(from_model(ManyNumerics)))
    def test_no_overflow_in_integer(self, manyints):
        pass

    @given(from_model(Customish))
    def test_custom_field(self, x):
        assert x.customish == u"a"

    def test_mandatory_fields_are_mandatory(self):
        self.assertRaises(InvalidArgument, from_model(Store).example)

    @checks_deprecated_behaviour
    def test_mandatory_fields_are_mandatory_old(self):
        self.assertRaises(InvalidArgument, models(Store).example)

    def test_mandatory_computed_fields_are_mandatory(self):
        with self.assertRaises(InvalidArgument):
            from_model(MandatoryComputed).example()

    @checks_deprecated_behaviour
    def test_mandatory_computed_fields_are_mandatory_old(self):
        with self.assertRaises(InvalidArgument):
            models(MandatoryComputed).example()

    def test_mandatory_computed_fields_may_not_be_provided(self):
        mc = from_model(MandatoryComputed, company=from_model(Company))
        self.assertRaises(RuntimeError, mc.example)

    @checks_deprecated_behaviour
    def test_mandatory_computed_fields_may_not_be_provided_old(self):
        mc = models(MandatoryComputed, company=models(Company))
        self.assertRaises(RuntimeError, mc.example)

    @checks_deprecated_behaviour
    @given(models(MandatoryComputed, company=default_value))
    def test_mandatory_computed_field_default(self, x):
        assert x.company.name == x.name + u"_company"

    @given(from_model(CustomishDefault, customish=infer))
    def test_customish_default_overridden_by_infer(self, x):
        assert x.customish == u"a"

    @given(from_model(CustomishDefault, customish=infer))
    def test_customish_infer_uses_registered_instead_of_default(self, x):
        assert x.customish == u"a"

    @checks_deprecated_behaviour
    @given(models(CustomishDefault, customish=default_value))
    def test_customish_default_generated(self, x):
        assert x.customish == u"b"

    @given(from_model(OddFields))
    def test_odd_fields(self, x):
        assert isinstance(x.uuid, UUID)
        assert isinstance(x.slug, text_type)
        assert u" " not in x.slug
        assert isinstance(x.ipv4, text_type)
        assert len(x.ipv4.split(".")) == 4
        assert all(int(i) in range(256) for i in x.ipv4.split("."))
        assert isinstance(x.ipv6, text_type)
        assert set(x.ipv6).issubset(set(u"0123456789abcdefABCDEF:."))

    @given(from_model(ManyTimes))
    def test_time_fields(self, x):
        assert isinstance(x.time, dt.time)
        assert isinstance(x.date, dt.date)
        assert isinstance(x.duration, dt.timedelta)

    @given(from_model(Company))
    def test_no_null_in_charfield(self, x):
        # regression test for #1045.  Company just has a convenient CharField.
        assert u"\x00" not in x.name

    @given(binary(min_size=10))
    def test_foreign_key_primary(self, buf):
        # Regression test for #1307
        company_strategy = from_model(Company, name=just("test"))
        strategy = from_model(
            CompanyExtension, company=company_strategy, self_modifying=just(2)
        )
        try:
            ConjectureData.for_buffer(buf).draw(strategy)
        except HypothesisException:
            reject()
        # Draw again with the same buffer. This will cause a duplicate
        # primary key.
        ConjectureData.for_buffer(buf).draw(strategy)
        assert CompanyExtension.objects.all().count() == 1
 def test_mandatory_fields_are_mandatory_old(self):
     self.assertRaises(InvalidArgument, models(Store).example)
Ejemplo n.º 45
0
 def test_can_get_examples(self):
     for _ in range(200):
         models(Company).example()
Ejemplo n.º 46
0
        "firstName": {"type": "string"},
        "lastName": {"type": "string"},
        "age": {"description": "Age", "type": "integer", "minimum": 0},
    },
    "required": ["firstName", "lastName"],
}

EXAMPLE_BAD_SCHEMA1 = "{'why is a string in a dict?'}"
EXAMPLE_BAD_SCHEMA2 = '"[]"'
EXAMPLE_BAD_SCHEMA3 = '"af[]23"'


UserGenerator = models(
    User,
    username=strategies.text(max_size=30),
    first_name=strategies.text(max_size=30),
    last_name=strategies.text(max_size=30),
    email=strategies.just("*****@*****.**"),
)

SurveyGenerator = models(Survey, schema=strategies.just(EXAMPLE_SCHEMA), created_by=UserGenerator)


SurveyGoalData = strategies.fixed_dictionaries(
    mapping={
        "schema": strategies.one_of(
            strategies.just(EXAMPLE_SCHEMA),
            strategies.text(),
            strategies.just(EXAMPLE_BAD_SCHEMA1),
            strategies.just(EXAMPLE_BAD_SCHEMA2),
            strategies.just(EXAMPLE_BAD_SCHEMA3),