def handle(self, *args, **options):
        image_folder, created = ImageFolder.objects.get_or_create(name='colors')

        for i, color in enumerate(self.get_colors()):
            image, created = Image.objects.get_or_create(user=None, name=color)

            size = (5, 5)
            im = PILImage.new("RGB", size, color)
            # im = ImageOps.expand(im, border=5, fill='orange')
            string_io = StringIO()
            try:
                im.save(string_io, format='png')
                content = string_io.getvalue()
                image.image.save(
                    '{0}.png'.format(color),
                    ContentFile(content)
                )
                image.save()

                Image2Folder.objects.get_or_create(
                    folder=image_folder,
                    image=image,
                    ordering=i,
                )
            finally:
                string_io.close()
Exemple #2
0
 def _choices_as_array(self):
     from django.utils.six import StringIO
     valuebuffer = StringIO(self.list_values)
     choices = [[item.strip(), item.strip()]
                for item in valuebuffer.readlines()]
     valuebuffer.close()
     return choices
Exemple #3
0
class ChangepasswordManagementCommandTestCase(TestCase):

    def setUp(self):
        self.user = models.User.objects.create_user(username='******', password='******')
        self.stdout = StringIO()
        self.stderr = StringIO()

    def tearDown(self):
        self.stdout.close()
        self.stderr.close()

    def test_that_changepassword_command_changes_joes_password(self):
        " Executing the changepassword management command should change joe's password "
        self.assertTrue(self.user.check_password('qwerty'))
        command = changepassword.Command()
        command._get_pass = lambda *args: 'not qwerty'

        command.execute("joe", stdout=self.stdout)
        command_output = self.stdout.getvalue().strip()

        self.assertEqual(command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'")
        self.assertTrue(models.User.objects.get(username="******").check_password("not qwerty"))

    def test_that_max_tries_exits_1(self):
        """
        A CommandError should be thrown by handle() if the user enters in
        mismatched passwords three times.
        """
        command = changepassword.Command()
        command._get_pass = lambda *args: args or 'foo'

        with self.assertRaises(CommandError):
            command.execute("joe", stdout=self.stdout, stderr=self.stderr)
Exemple #4
0
class MultiDBChangepasswordManagementCommandTestCase(TestCase):
    multi_db = True

    def setUp(self):
        self.user = models.User.objects.db_manager("other").create_user(username="******", password="******")
        self.stdout = StringIO()

    def tearDown(self):
        self.stdout.close()

    def test_that_changepassword_command_with_database_option_uses_given_db(self):
        """
        Executing the changepassword management command with a database option
        should operate on the specified DB
        """
        self.assertTrue(self.user.check_password("qwerty"))
        command = changepassword.Command()
        command._get_pass = lambda *args: "not qwerty"

        command.execute(username="******", database="other", stdout=self.stdout)
        command_output = self.stdout.getvalue().strip()

        self.assertEqual(
            command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'"
        )
        self.assertTrue(models.User.objects.using("other").get(username="******").check_password("not qwerty"))
Exemple #5
0
class MultiDBChangepasswordManagementCommandTestCase(TestCase):
    multi_db = True

    def setUp(self):
        self.user = models.User.objects.db_manager('other').create_user(
            username='******', password='******')
        self.stdout = StringIO()

    def tearDown(self):
        self.stdout.close()

    def test_that_changepassword_command_with_database_option_uses_given_db(
            self):
        """
        Executing the changepassword management command with a database option
        should operate on the specified DB
        """
        self.assertTrue(self.user.check_password('qwerty'))
        command = changepassword.Command()
        command._get_pass = lambda *args: 'not qwerty'

        command.execute(username="******", database='other', stdout=self.stdout)
        command_output = self.stdout.getvalue().strip()

        self.assertEqual(
            command_output,
            "Changing password for user 'joe'\nPassword changed successfully for user 'joe'"
        )
        self.assertTrue(
            models.User.objects.using('other').get(
                username="******").check_password("not qwerty"))
Exemple #6
0
class ChangepasswordManagementCommandTestCase(TestCase):

    def setUp(self):
        self.user = models.User.objects.create_user(username='******', password='******')
        self.stdout = StringIO()
        self.stderr = StringIO()

    def tearDown(self):
        self.stdout.close()
        self.stderr.close()

    def test_that_changepassword_command_changes_joes_password(self):
        "Executing the changepassword management command should change joe's password"
        self.assertTrue(self.user.check_password('qwerty'))
        command = changepassword.Command()
        command._get_pass = lambda *args: 'not qwerty'

        command.execute("joe", stdout=self.stdout)
        command_output = self.stdout.getvalue().strip()

        self.assertEqual(command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'")
        self.assertTrue(models.User.objects.get(username="******").check_password("not qwerty"))

    def test_that_max_tries_exits_1(self):
        """
        A CommandError should be thrown by handle() if the user enters in
        mismatched passwords three times.
        """
        command = changepassword.Command()
        command._get_pass = lambda *args: args or 'foo'

        with self.assertRaises(CommandError):
            command.execute("joe", stdout=self.stdout, stderr=self.stderr)
    def get_command_output(self, cmd, *cmd_args, **cmd_options):
        file_obj = StringIO()
        cmd_options.update(stdout=file_obj)
        call_command(cmd, *cmd_args, **cmd_options)
        output = file_obj.getvalue()

        file_obj.close()
        return output
Exemple #8
0
def clean_zonefile(data):
    EOL = '\n'
    lines = []
    f = StringIO(data)
    for line in f:
        line = line.strip()
        if line:
            lines.append(line)
    f.close()
    return EOL.join(lines)
 def run_cmd_verify_stdout(self, min_lines, cmd, *args, **kwargs):
     "Runs the given command with full verbosity and checks there are output strings"
     args = self.source_arg + args
     kwargs.setdefault('verbosity', 3)
     buf = StringIO()
     call_command(cmd, stdout=buf, stderr=buf, *args, **kwargs)
     output = buf.getvalue().splitlines()
     buf.close()
     self.assertGreaterEqual(len(output), min_lines)
     return output
 def _create_csv(self):
     """
     StringIO holds the csv data in a memory buffer that acts
     like a regular file. Python's csv library does all the
     heaving lifting and worrying about creating the csv properly.
     """
     f = StringIO()
     try:
         self._write_csv_contents(f)
         return f.getvalue()
     finally:
         f.close()
Exemple #11
0
 def test_stealth_table_name_filter_option(self):
     out = StringIO()
     # Lets limit the introspection to tables created for models of this
     # application
     call_command('inspectdb',
                  table_name_filter=lambda tn:tn.startswith('inspectdb_'),
                  stdout=out)
     error_message = "inspectdb has examined a table that should have been filtered out."
     # contrib.contenttypes is one of the apps always installed when running
     # the Django test suite, check that one of its tables hasn't been
     # inspected
     self.assertNotIn("class DjangoContentType(models.Model):", out.getvalue(), msg=error_message)
     out.close()
Exemple #12
0
 def test_stealth_table_name_filter_option(self):
     out = StringIO()
     # Lets limit the introspection to tables created for models of this
     # application
     call_command('inspectdb',
                  table_name_filter=lambda tn: tn.startswith('inspectdb_'),
                  stdout=out)
     error_message = "inspectdb has examined a table that should have been filtered out."
     # contrib.contenttypes is one of the apps always installed when running
     # the Django test suite, check that one of its tables hasn't been
     # inspected
     self.assertNotIn("class DjangoContentType(models.Model):",
                      out.getvalue(),
                      msg=error_message)
     out.close()
Exemple #13
0
 def test_attribute_name_not_python_keyword(self):
     out = StringIO()
     # Lets limit the introspection to tables created for models of this
     # application
     call_command('inspectdb',
                  table_name_filter=lambda tn:tn.startswith('inspectdb_'),
                  stdout=out)
     error_message = "inspectdb generated an attribute name which is a python keyword"
     self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", out.getvalue(), msg=error_message)
     # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
     self.assertIn("from_field = models.ForeignKey('InspectdbPeople')", out.getvalue())
     self.assertIn("people_pk = models.ForeignKey(InspectdbPeople, primary_key=True)",
         out.getvalue())
     self.assertIn("people_unique = models.ForeignKey(InspectdbPeople, unique=True)",
         out.getvalue())
     out.close()
Exemple #14
0
    def test_createsuperuser_command_with_database_option(self):
        " createsuperuser command should operate on specified DB"
        new_io = StringIO()

        call_command("createsuperuser",
                     interactive=False,
                     username="******",
                     email="*****@*****.**",
                     database='other',
                     stdout=new_io)
        command_output = new_io.getvalue().strip()

        self.assertEqual(command_output, 'Superuser created successfully.')

        u = models.User.objects.using('other').get(username="******")
        self.assertEqual(u.email, '*****@*****.**')

        new_io.close()
Exemple #15
0
class TestCommand:
    def setup(self):
        self.stdout = StringIO()

    def teardown(self):
        self.stdout.close()

    @mock.patch('rhome.watchdog.pushover.requests.post')
    def test_handle(self, request_mock, settings):
        request_mock.return_value = requests.Response()
        request_mock.return_value.status_code = 200

        settings.DEBUG = True
        metric = MetricFactory.create()
        RecordFactory.create(value=3, metric=metric)
        WatchdogFactory.create(metric=metric)

        assert Command().execute(stdout=self.stdout) is None
class TestCommand:
    def setup(self):
        self.stdout = StringIO()

    def teardown(self):
        self.stdout.close()

    @mock.patch('terrarium.watchdog.pushover.requests.post')
    def test_handle(self, request_mock, settings):
        request_mock.return_value = requests.Response()
        request_mock.return_value.status_code = 200

        settings.DEBUG = True
        metric = MetricFactory.create()
        RecordFactory.create(value=3, metric=metric)
        WatchdogFactory.create(metric=metric)

        assert Command().execute(stdout=self.stdout) is None
Exemple #17
0
    def test_createsuperuser_command_with_database_option(self):
        " createsuperuser command should operate on specified DB"
        new_io = StringIO()

        call_command("createsuperuser",
            interactive=False,
            username="******",
            email="*****@*****.**",
            database='other',
            stdout=new_io
        )
        command_output = new_io.getvalue().strip()

        self.assertEqual(command_output, 'Superuser created successfully.')

        u = models.User.objects.using('other').get(username="******")
        self.assertEqual(u.email, '*****@*****.**')

        new_io.close()
Exemple #18
0
 def test_attribute_name_not_python_keyword(self):
     out = StringIO()
     # Lets limit the introspection to tables created for models of this
     # application
     call_command('inspectdb',
                  table_name_filter=lambda tn: tn.startswith('inspectdb_'),
                  stdout=out)
     error_message = "inspectdb generated an attribute name which is a python keyword"
     self.assertNotIn("from = models.ForeignKey(InspectdbPeople)",
                      out.getvalue(),
                      msg=error_message)
     # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
     self.assertIn("from_field = models.ForeignKey('InspectdbPeople')",
                   out.getvalue())
     self.assertIn(
         "people_pk = models.ForeignKey(InspectdbPeople, primary_key=True)",
         out.getvalue())
     self.assertIn(
         "people_unique = models.ForeignKey(InspectdbPeople, unique=True)",
         out.getvalue())
     out.close()
Exemple #19
0
class BufferedFile(File):
    def __init__(self, file_object, mode, name=None):
        self.file_object = file_object
        self.mode = mode
        if 'b' in mode:
            self.stream = BytesIO()
        else:
            self.stream = StringIO()

        self.stream_size = 0

    def close(self):
        self.file_object.close()
        self.stream.close()

    def read(self, size=None):
        if size is None:
            size = -1

        if size == -1 or size > self.stream_size:
            while True:
                position = self.stream.tell()
                chunk = self._get_file_object_chunk()
                if chunk:
                    self.stream_size += len(chunk)
                    self.stream.write(chunk)
                    self.stream.seek(position)
                    if self.stream_size >= size and size != -1:
                        break
                else:
                    break

        if size:
            read_size = min(size, self.stream_size)
            self.stream_size -= read_size
        else:
            read_size = None

        return self.stream.read(read_size)
Exemple #20
0
def create_mosaico(mosaico_pk):
    mosaico = Mosaico.objects.get(pk=mosaico_pk)
    mosaico.status = Mosaico.RENDERING
    mosaico.save()

    result = mosaicify(
        target=mosaico.target.path,
        sources=mosaico.images(),
        tiles=128,
        zoom=4,
    )
    result._initialize()
    string_io = StringIO()
    try:
        result._mosaic.blob.save(string_io, format='png')
        content = string_io.getvalue()
        mosaico.result_image.save('result_{0}.png'.format(mosaico.pk),
                                  ContentFile(content))
        mosaico.status = Mosaico.FINISHED
    finally:
        string_io.close()

    mosaico.save()
Exemple #21
0
    def handle(self, *args, **options):
        image_folder, created = ImageFolder.objects.get_or_create(
            name='colors')

        for i, color in enumerate(self.get_colors()):
            image, created = Image.objects.get_or_create(user=None, name=color)

            size = (5, 5)
            im = PILImage.new("RGB", size, color)
            # im = ImageOps.expand(im, border=5, fill='orange')
            string_io = StringIO()
            try:
                im.save(string_io, format='png')
                content = string_io.getvalue()
                image.image.save('{0}.png'.format(color), ContentFile(content))
                image.save()

                Image2Folder.objects.get_or_create(
                    folder=image_folder,
                    image=image,
                    ordering=i,
                )
            finally:
                string_io.close()
Exemple #22
0
 def _choices_as_array(self):
     from django.utils.six import StringIO
     valuebuffer = StringIO(self.list_values)
     choices = [[item.strip(), item.strip()] for item in valuebuffer.readlines()]
     valuebuffer.close()
     return choices