コード例 #1
0
def test_single_seen():
    """If relation is single and if traversed more than once - it fails."""
    simple_model = autofixture.create_one(SimpleModel)
    autofixture.create(FKModel, 3, field_values={'fk': simple_model})

    queryset = FKModel.deep.prefetch_related('fk', 'fk__fks__fk')
    list(queryset)
コード例 #2
0
ファイル: createdata.py プロジェクト: DESHRAJ/HTTP_200
    def handle(self, *attrs, **options):

        # for assigning Groups -
        #   0:No group
        #   1:StudentGroup
        #   2:FacultyGroup
        logger.debug("Creating a Faculty Superuser with username: admin and password %s" % admin_md5)
        admin = autofixture.create_one('auth.User',
                                       field_values={'username': '******',
                                                     'password': admin_md5,
                                                     'groups': ['2'],
                                                     'is_superuser': True,
                                                     })

        adminDetail = autofixture.create_one('profiles.FacultyDetail',
                                             field_values={
                                                 'user': admin
                                             })

        logger.debug("Creating 10 Notices")
        autofixture.create('notices.Notice',
                           count=10,
                           follow_fk=True,
                           field_values={
                               'faculty': adminDetail
                           })

        logger.debug("Creating Student type User with username 'student' and password %s" % student_md5)
        student = autofixture.create_one('auth.User',
                                         field_values={
                                             'username': '******',
                                             'password': student_md5,
                                             'groups': ['1'],
                                             'is_superuser': True,
                                         })

        autofixture.create_one('profiles.StudentDetail', field_values={'user': student})

        logger.debug("Creating 10 random Faculty Accounts")
        for _ in xrange(0, 10):
            test_faculty = autofixture.create_one('auth.User',
                                                  field_values={
                                                      'password': default_md5,
                                                      'groups': ['2']
                                                  })
            autofixture.create_one('profiles.FacultyDetail', field_values={'user': test_faculty})

        logger.debug("Creating 10 random Notices")
        autofixture.create('notices.Notice', count=10, follow_fk=True)

        logger.debug("Creating 10 random Student Accounts")
        for _ in range(0, 10):
            test_student = autofixture.create_one('auth.User',
                                                  field_values={
                                                      'password': default_md5,
                                                      'groups': ['1']
                                                  })
            autofixture.create_one('profiles.StudentDetail', field_values={'user': test_student})
コード例 #3
0
    def handle(self, *args, **kwargs):
        p = Profiler()

        print('Creating users')
        users = autofixture.create('auth.User', 20, overwrite_defaults=True)
        user = users[0]
        p.authorise_with(user)

        print('Creating regions')
        autofixture.create('geo.Region',
                           5,
                           field_values={
                               'created_by': user,
                           })

        print('Creating projects')
        Project.objects.all().delete()
        autofixture.create_one('project.Project',
                               field_values={
                                   'created_by': user,
                               })
        project = Project.objects.first()
        if not ProjectMembership.objects.filter(project=project, member=user)\
                .exists():
            ProjectMembership.objects.create(project=project,
                                             member=user,
                                             role='admin')

        print('Creating leads')
        # create_many_leads(1000, user, project)
        autofixture.create('lead.Lead',
                           100,
                           field_values={
                               'created_by': user,
                           })

        print('Starting profiling')
        p.profile_get('/api/v1/leads/?'
                      'status=pending&'
                      'published_on__lt=2016-01-10&'
                      'assignee={0}&'
                      'search=lorem&'
                      'limit=100&'
                      ''.format(users[2].id))

        p.__del__()
コード例 #4
0
 def test_values_class(self):
     autofixture.register(BasicModel, BasicValueFixture)
     for obj in autofixture.create(BasicModel, 10):
         self.assertEqual(obj.chars, 'foo')
         self.assertEqual(obj.shortchars, 'a')
         self.assertEqual(obj.blankchars, 'bar')
         self.assertEqual(obj.nullchars, 'spam')
         self.assertTrue(1 <= obj.intfield <= 13)
コード例 #5
0
ファイル: tests.py プロジェクト: dominno/django-autofixture
 def test_values_class(self):
     autofixture.register(BasicModel, BasicValueFixture)
     for obj in autofixture.create(BasicModel, 10):
         self.assertEqual(obj.chars, 'foo')
         self.assertEqual(obj.shortchars, 'a')
         self.assertEqual(obj.blankchars, 'bar')
         self.assertEqual(obj.nullchars, 'spam')
         self.assertTrue(1 <= obj.intfield <= 13)
コード例 #6
0
 def test_overwrite_attributes(self):
     autofixture.register(SimpleModel, SimpleAutoFixture)
     for obj in autofixture.create(SimpleModel,
                                   10,
                                   field_values={'name': 'bar'}):
         self.assertEqual(obj.name, 'bar')
     obj = autofixture.create_one(SimpleModel, field_values={'name': 'bar'})
     self.assertEqual(obj.name, 'bar')
コード例 #7
0
ファイル: tests.py プロジェクト: dominno/django-autofixture
 def test_overwrite_attributes(self):
     autofixture.register(SimpleModel, SimpleAutoFixture)
     for obj in autofixture.create(
             SimpleModel, 10, field_values={'name': 'bar'}):
         self.assertEqual(obj.name, 'bar')
     obj = autofixture.create_one(
         SimpleModel, field_values={'name': 'bar'})
     self.assertEqual(obj.name, 'bar')
コード例 #8
0
ファイル: tests.py プロジェクト: edavis/srl
 def test_category_to_outline(self):
     category = autofixture.create_one(Category, field_values={
         "owner": self.owner,
         "name": "category",
     })
     feeds = autofixture.create(Feed, 10, field_values={
         "owner": self.owner,
         "category": category,
     })
     category_element = etree.Element("outline", text=category.name)
     for feed in Feed.objects.all():
         category_element.append(feed.to_outline())
     self.elements_equal(category.to_outline(), category_element)
コード例 #9
0
    def test_transaction_objects(self):
        """
		Test that the transact and transact_many methods work.
		"""

        account = Account.objects.get(pk=1)
        account.check_bal(force=True)
        # See that the balances are being updated correctly
        # and that the check_bal function works in force mode
        self.assertEquals(account.check_bal(), account.bal)

        # Make sure transactions are being added as soon as they are created
        cur_hist_length = len(account.history.all())
        new_transactions = autofixture.create(
            Transaction, 4, field_values={"amount": random_decimal_generator(), "user": account.user}
        )

        self.assertEquals(len(account.history.all()), cur_hist_length + 4)
コード例 #10
0
    def handle(self, *attrs, **options):
        error_option = None
        #
        # follow options
        #
        if options["no_follow_fk"] is None:
            follow_fk = None
        else:
            follow_fk = False
        if options["no_follow_m2m"] is None:
            follow_m2m = None
            # this is the only chance for the follow_m2m options to be parsed
            if options["follow_m2m"]:
                try:
                    value = options["follow_m2m"].split(",")
                    if len(value) == 1 and value[0].count(":") == 1:
                        follow_m2m = [int(i) for i in value[0].split(":")]
                    else:
                        follow_m2m = {}
                        for field in value:
                            key, minval, maxval = field.split(":")
                            follow_m2m[key] = int(minval), int(maxval)
                except ValueError:
                    error_option = "--follow-m2m={0}".format(options["follow_m2m"])
        else:
            follow_m2m = False
        #
        # generation options
        #
        if options["generate_fk"] is None:
            generate_fk = None
        else:
            generate_fk = options["generate_fk"].split(",")
        generate_m2m = None
        if options["generate_m2m"]:
            try:
                value = [v for v in options["generate_m2m"].split(",") if v]
                if len(value) == 1 and value[0].count(":") == 1:
                    generate_m2m = [int(i) for i in value[0].split(":")]
                else:
                    generate_m2m = {}
                    for field in value:
                        key, minval, maxval = field.split(":")
                        generate_m2m[key] = int(minval), int(maxval)
            except ValueError:
                error_option = "--generate-m2m={0}".format(options["generate_m2m"])

        if error_option:
            raise CommandError(
                u"Invalid option {0}\nExpected: {1}=field:min:max,field2:min:max... (min and max must be numbers)".format(
                    error_option, error_option.split("=", 1)[0]
                )
            )

        use = options["use"]
        if use:
            use = use.split(".")
            use = getattr(importlib.import_module(".".join(use[:-1])), use[-1])

        overwrite_defaults = options["overwrite_defaults"]
        self.verbosity = int(options["verbosity"])

        models = []
        for attr in attrs:
            try:
                app_label, model_label = attr.split(".")
                model_label, count = model_label.split(":")
                count = int(count)
            except ValueError:
                raise CommandError(
                    u"Invalid argument: {0}\nExpected: app_label.ModelName:count (count must be a number)".format(attr)
                )
            model = get_model(app_label, model_label)
            if not model:
                raise CommandError(u"Unknown model: {0}.{1}".format(app_label, model_label))
            models.append((model, count))

        signals.instance_created.connect(self.print_instance)

        autofixture.autodiscover()

        kwargs = {
            "overwrite_defaults": overwrite_defaults,
            "follow_fk": follow_fk,
            "generate_fk": generate_fk,
            "follow_m2m": follow_m2m,
            "generate_m2m": generate_m2m,
        }

        for model, count in models:
            if use:
                fixture = use(model, **kwargs)
                fixture.create(count)
            else:
                autofixture.create(model, count, **kwargs)
コード例 #11
0
ファイル: tests.py プロジェクト: dominno/django-autofixture
 def test_create(self):
     autofixture.register(SimpleModel, SimpleAutoFixture)
     for obj in autofixture.create(SimpleModel, 10):
         self.assertEqual(obj.name, 'foo')
     obj = autofixture.create_one(SimpleModel)
     self.assertEqual(obj.name, 'foo')
コード例 #12
0
    def handle(self, *attrs, **options):
        error_option = None
        #
        # follow options
        #
        if options['no_follow_fk'] is None:
            follow_fk = None
        else:
            follow_fk = False
        if options['no_follow_m2m'] is None:
            follow_m2m = None
            # this is the only chance for the follow_m2m options to be parsed
            if options['follow_m2m']:
                try:
                    value = options['follow_m2m'].split(',')
                    if len(value) == 1 and value[0].count(':') == 1:
                        follow_m2m = [int(i) for i in value[0].split(':')]
                    else:
                        follow_m2m = {}
                        for field in value:
                            key, minval, maxval = field.split(':')
                            follow_m2m[key] = int(minval), int(maxval)
                except ValueError:
                    error_option = '--follow-m2m={0}'.format(options['follow_m2m'])
        else:
            follow_m2m = False
        #
        # generation options
        #
        if options['generate_fk'] is None:
            generate_fk = None
        else:
            generate_fk = options['generate_fk'].split(',')
        generate_m2m = None
        if options['generate_m2m']:
            try:
                value = [v for v in options['generate_m2m'].split(',') if v]
                if len(value) == 1 and value[0].count(':') == 1:
                    generate_m2m = [int(i) for i in value[0].split(':')]
                else:
                    generate_m2m = {}
                    for field in value:
                        key, minval, maxval = field.split(':')
                        generate_m2m[key] = int(minval), int(maxval)
            except ValueError:
                error_option = '--generate-m2m={0}'.format(options['generate_m2m'])

        if error_option:
            raise CommandError(
                u'Invalid option {0}\n'
                u'Expected: {1}=field:min:max,field2:min:max... (min and max must be numbers)'.format(
                    error_option,
                    error_option.split('=', 1)[0]))

        use = options['use']
        if use:
            use = use.split('.')
            use = getattr(importlib.import_module('.'.join(use[:-1])), use[-1])

        overwrite_defaults = options['overwrite_defaults']
        self.verbosity = int(options['verbosity'])

        models = []
        for attr in attrs:
            try:
                app_label, model_label = attr.split('.')
                model_label, count = model_label.split(':')
                count = int(count)
            except ValueError:
                raise CommandError(
                    u'Invalid argument: {0}\n'
                    u'Expected: app_label.ModelName:count '
                    u'(count must be a number)'.format(attr))
            model = get_model(app_label, model_label)
            if not model:
                raise CommandError(
                    u'Unknown model: {0}.{1}'.format(app_label, model_label))
            models.append((model, count))

        signals.instance_created.connect(
            self.print_instance)

        autofixture.autodiscover()

        kwargs = {
            'overwrite_defaults': overwrite_defaults,
            'follow_fk': follow_fk,
            'generate_fk': generate_fk,
            'follow_m2m': follow_m2m,
            'generate_m2m': generate_m2m,
        }

        for model, count in models:
            if use:
                fixture = use(model, **kwargs)
                fixture.create(count)
            else:
                autofixture.create(model, count, **kwargs)
コード例 #13
0
    for i in artist_images:
        autofixture.create_one(
            "artists.ArtistImage",
            field_values={"url": i["url"], "width": i["width"], "height": i["height"], "artist": res},
        )

autofixture.create(
    "videos.Video",
    200,
    none_p=0,
    generate_fk=False,
    follow_m2m=(1, 2),
    field_values={
        "uploaded": True,
        "file_size": autofixture.generators.PositiveIntegerGenerator(),
        "is_private": autofixture.generators.BooleanGenerator(),
        "views": autofixture.generators.PositiveSmallIntegerGenerator(),
        "length": autofixture.generators.PositiveIntegerGenerator(),
        "uuid": autofixture.generators.ChoicesGenerator(values=possible_uuids),
        "name": autofixture.generators.LoremSentenceGenerator(max_length=140),
        "original_filename": autofixture.generators.StringGenerator(max_length=140),
        "height": 1080,
        "width": 1920,
    },
)

autofixture.create(
    "videos.Edge",
    200,
    none_p=0,
    field_values={
コード例 #14
0
import autofixture
from autofixture import AutoFixture, generators
from models import *
from datetime import datetime

print 'Setting up CMS fixtures'

CourseFixture = AutoFixture(Course,
    field_values={
      'name': generators.LoremWordGenerator(count=2)
      ,'full_name': generators.LoremSentenceGenerator()
      ,'description': generators.LoremHTMLGenerator()
      ,'schedule_no': generators.PositiveIntegerGenerator(min_value=222222)
      ,'start_date': generators.DateGenerator(max_date=datetime.today())
      ,'end_date': generators.DateGenerator(min_date=datetime.today())
      ,'active': generators.StaticGenerator(True)
    }
  )


autofixture.register(Course, CourseFixture)

courses = autofixture.create(Course, 3)
print courses
コード例 #15
0
    def handle(self, *attrs, **options):
        from django.db.models import get_model

        error_option = None
        #
        # follow options
        #
        if options['no_follow_fk'] is None:
            follow_fk = None
        else:
            follow_fk = False
        if options['no_follow_m2m'] is None:
            follow_m2m = None
            # this is the only chance for the follow_m2m options to be parsed
            if options['follow_m2m']:
                try:
                    value = options['follow_m2m'].split(',')
                    if len(value) == 1 and value[0].count(':') == 1:
                        follow_m2m = [int(i) for i in value[0].split(':')]
                    else:
                        follow_m2m = {}
                        for field in value:
                            key, minval, maxval = field.split(':')
                            follow_m2m[key] = int(minval), int(maxval)
                except ValueError:
                    error_option = '--follow-m2m={0}'.format(
                        options['follow_m2m'])
        else:
            follow_m2m = False
        #
        # generation options
        #
        if options['generate_fk'] is None:
            generate_fk = None
        else:
            generate_fk = options['generate_fk'].split(',')
        generate_m2m = None
        if options['generate_m2m']:
            try:
                value = [v for v in options['generate_m2m'].split(',') if v]
                if len(value) == 1 and value[0].count(':') == 1:
                    generate_m2m = [int(i) for i in value[0].split(':')]
                else:
                    generate_m2m = {}
                    for field in value:
                        key, minval, maxval = field.split(':')
                        generate_m2m[key] = int(minval), int(maxval)
            except ValueError:
                error_option = '--generate-m2m={0}'.format(
                    options['generate_m2m'])

        if error_option:
            raise CommandError(
                u'Invalid option {0}\n'
                u'Expected: {1}=field:min:max,field2:min:max... (min and max must be numbers)'
                .format(error_option,
                        error_option.split('=', 1)[0]))

        use = options['use']
        if use:
            use = use.split('.')
            use = getattr(import_module('.'.join(use[:-1])), use[-1])

        overwrite_defaults = options['overwrite_defaults']
        self.verbosity = int(options['verbosity'])

        models = []
        for attr in attrs:
            try:
                app_label, model_label = attr.split('.')
                model_label, count = model_label.split(':')
                count = int(count)
            except ValueError:
                raise CommandError(u'Invalid argument: {0}\n'
                                   u'Expected: app_label.ModelName:count '
                                   u'(count must be a number)'.format(attr))
            model = get_model(app_label, model_label)
            if not model:
                raise CommandError(u'Unknown model: {0}.{1}'.format(
                    app_label, model_label))
            models.append((model, count))

        signals.instance_created.connect(self.print_instance)

        autofixture.autodiscover()

        kwargs = {
            'overwrite_defaults': overwrite_defaults,
            'follow_fk': follow_fk,
            'generate_fk': generate_fk,
            'follow_m2m': follow_m2m,
            'generate_m2m': generate_m2m,
        }

        for model, count in models:
            if use:
                fixture = use(model, **kwargs)
                fixture.create(count)
            else:
                autofixture.create(model, count, **kwargs)
コード例 #16
0
 def test_create(self):
     autofixture.register(SimpleModel, SimpleAutoFixture)
     for obj in autofixture.create(SimpleModel, 10):
         self.assertEqual(obj.name, 'foo')
     obj = autofixture.create_one(SimpleModel)
     self.assertEqual(obj.name, 'foo')
コード例 #17
0
    def test_commit_kwarg(self):
        instances = autofixture.create(BasicModel, 3, commit=False)
        self.assertEqual([i.pk for i in instances], [None] * 3)

        instance = autofixture.create_one(BasicModel, commit=False)
        self.assertEqual(instance.pk, None)
コード例 #18
0
    def populate_database(self):

        autofixture.create(SUser, 200)

        autofixture.create(Group, 1)
        autofixture.create(Event, 3)
        autofixture.create(OptionGroup, 10)
        autofixture.create(Option, 30)

        autofixture.create(Attend, 300)
        autofixture.create(Selection, 500)
コード例 #19
0
ファイル: createdata.py プロジェクト: spyshiv/HTTP_200
    def handle(self, *attrs, **options):

        # for assigning Groups -
        #   0:No group
        #   1:StudentGroup
        #   2:FacultyGroup
        logger.debug(
            "Creating a Faculty Superuser with username: admin and password %s"
            % admin_md5)
        admin = autofixture.create_one('auth.User',
                                       field_values={
                                           'username': '******',
                                           'password': admin_md5,
                                           'groups': ['2'],
                                           'is_superuser': True,
                                       })

        adminDetail = autofixture.create_one('profiles.FacultyDetail',
                                             field_values={'user': admin})

        logger.debug("Creating 10 Notices")
        autofixture.create('notices.Notice',
                           count=10,
                           follow_fk=True,
                           field_values={'faculty': adminDetail})

        logger.debug(
            "Creating Student type User with username 'student' and password %s"
            % student_md5)
        student = autofixture.create_one('auth.User',
                                         field_values={
                                             'username': '******',
                                             'password': student_md5,
                                             'groups': ['1'],
                                             'is_superuser': True,
                                         })

        autofixture.create_one('profiles.StudentDetail',
                               field_values={'user': student})

        logger.debug("Creating 10 random Faculty Accounts")
        for _ in xrange(0, 10):
            test_faculty = autofixture.create_one('auth.User',
                                                  field_values={
                                                      'password': default_md5,
                                                      'groups': ['2']
                                                  })
            autofixture.create_one('profiles.FacultyDetail',
                                   field_values={'user': test_faculty})

        logger.debug("Creating 10 random Notices")
        autofixture.create('notices.Notice', count=10, follow_fk=True)

        logger.debug("Creating 10 random Student Accounts")
        for _ in range(0, 10):
            test_student = autofixture.create_one('auth.User',
                                                  field_values={
                                                      'password': default_md5,
                                                      'groups': ['1']
                                                  })
            autofixture.create_one('profiles.StudentDetail',
                                   field_values={'user': test_student})
コード例 #20
0
ファイル: base.py プロジェクト: aschriner/django-autofixture
    def test_commit_kwarg(self):
        instances = autofixture.create(BasicModel, 3, commit=False)
        self.assertEqual([i.pk for i in instances], [None] * 3)

        instance = autofixture.create_one(BasicModel, commit=False)
        self.assertEqual(instance.pk, None)
コード例 #21
0
ファイル: autofixtures.py プロジェクト: Northshoot/hintaas
@author: lauril
'''
    
from autofixture import generators, register
from autofixture.base import AutoFixture    
from tests.models import TestTemplate
from datetime import datetime
import random
import string

class ImageNameGenerator(generators.Generator):
    
    def generate(self):
        return 'i-'+str(self.id_generator(size=10))

    def id_generator(self,size=6, chars=string.ascii_lowercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))

import autofixture
list = autofixture.create('tests.models.TestTemplate', 10, 
                     field_values={
                                  'image': ImageNameGenerator(),
                                  'image': generators.FirstNameGenerator(),
                                  'image': generators.StaticGenerator('test_template.xml'),
                                  'image': generators.LoremGenerator(max_length=300),
                                  'image': staticmethod(lambda: random.choice((10,200))),
                                  'image': generators.StaticGenerator('https://localhost:9493')
                                  
                                  })

print list