def test_composite_or_for_always_false(self):
     permission_class = CompositeOr(AlwaysFalsePermission,
                                    AlwaysFalsePermission)
     self.assertFalse(permission_class().has_permission(
         mock.Mock(), mock.Mock()))
     self.assertFalse(permission_class().has_object_permission(
         mock.Mock(), mock.Mock(), mock.Mock()))
 def test_composite_or_for_both_right(self):
     permission_class = CompositeOr(AlwaysTruePermission,
                                    AlwaysFalsePermission)
     self.assertTrue(permission_class().has_permission(
         mock.Mock(), mock.Mock()))
     self.assertTrue(permission_class().has_object_permission(
         mock.Mock(), mock.Mock(), mock.Mock()))
    def test_composite_wrapper_or_right(self):
        permission_class = Composite(AlwaysTruePermission) | \
                           Composite(AlwaysFalsePermission)

        self.assertTrue(permission_class().has_permission(
            mock.Mock(), mock.Mock()))
        self.assertTrue(permission_class().has_object_permission(
            mock.Mock(), mock.Mock(), mock.Mock()))
    def test_unknown_msg_handling(self):
        msg = mock.Mock()
        msg.connection.identity = "+11234567890"
        msg.connections = [mock.Mock()]
        msg.text = "some RANDOM garbage"

        router = mock.Mock()
        app = SubscriptionApp(router)

        app.handle(msg)
Exemple #5
0
    def test_messenger_send(self):
        received_msg = mock.Mock()
        msgr = Messenger(received_msg)

        msg = mock.Mock()
        msg_text = "Shake it fast, WATCH YO SELF"
        msg.contents = mock.Mock(return_value=msg_text)
        msgr.send([msg])

        received_msg.respond.assert_any_call(msg_text)
    def test_unknown_msg_handling(self):
        messenger = mock.Mock()
        subscription_state = mock.Mock()
        subscription_state.state = SubscriptionStates.UNSUBSCRIBED_STATE
        subscriber = mock.Mock()

        courier = SubscriptionCourier(messenger, subscription_state,
                                      subscriber)
        courier.receive("Keanu Reeves is a great actor")

        assert subscription_state.subscribe_help.call_count == 1
    def test_unsupported_lang_selection(self):
        messenger = mock.Mock()
        subscription_state = mock.Mock()
        subscription_state.state = SubscriptionStates.SELECTING_LANG_STATE
        subscriber = mock.Mock()

        courier = SubscriptionCourier(messenger, subscription_state,
                                      subscriber)
        courier.receive("?")

        assert subscription_state.unknown_lang_selected.call_count == 1
    def test_reselect_lang(self):
        messenger = mock.Mock()
        subscription_state = mock.Mock()
        subscription_state.state = SubscriptionStates.COMPLETE_STATE
        subscriber = mock.Mock()

        courier = SubscriptionCourier(messenger, subscription_state,
                                      subscriber)
        courier.receive("cambio de lengua")

        assert subscription_state.reselect_language.call_count == 1
Exemple #9
0
def _get_storage_mock():
    oid = '012345678901234567890123'

    mongo_storage = mock.Mock(spec=MongoStorage)
    mongo_storage.save.return_value = oid
    mongo_storage.url.return_value = '/storage/django_mongo_storage/document/0/{}/'.format(
        oid)
    mongo_storage.collection = 'test'
    mongo_storage.get_file_name.return_value = 'test.txt'
    mongo_storage.delete = mock.Mock()

    return mongo_storage
Exemple #10
0
 def test_makemigrations_interactive_by_default(self):
     """
     Makes sure that the user is prompted to merge by default if there are
     conflicts and merge is True. Answer negative to differentiate it from
     behavior when --noinput is specified.
     """
     # Monkeypatch interactive questioner to auto reject
     out = six.StringIO()
     with mock.patch('django.db.migrations.questioner.input',
                     mock.Mock(return_value='N')):
         try:
             with self.temporary_migration_module(
                     module="migrations.test_migrations_conflict"
             ) as migration_dir:
                 call_command("makemigrations",
                              "migrations",
                              merge=True,
                              stdout=out)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 # This will fail if interactive is False by default
                 self.assertFalse(os.path.exists(merge_file))
         except CommandError:
             self.fail(
                 "Makemigrations failed while running interactive questioner"
             )
         self.assertNotIn("Created new merge migration", out.getvalue())
Exemple #11
0
 def test_makemigrations_interactive_accept(self):
     """
     Makes sure that makemigrations enters interactive mode and merges properly.
     """
     # Monkeypatch interactive questioner to auto accept
     with mock.patch('django.db.migrations.questioner.input',
                     mock.Mock(return_value='y')):
         out = six.StringIO()
         try:
             with self.temporary_migration_module(
                     module="migrations.test_migrations_conflict"
             ) as migration_dir:
                 call_command("makemigrations",
                              "migrations",
                              merge=True,
                              interactive=True,
                              stdout=out)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 self.assertTrue(os.path.exists(merge_file))
         except CommandError:
             self.fail(
                 "Makemigrations failed while running interactive questioner"
             )
         self.assertIn("Created new merge migration",
                       force_text(out.getvalue()))
Exemple #12
0
 def test_makemigrations_unspecified_app_with_conflict_merge(self):
     """
     Makes sure that makemigrations does not create a merge for an
     unspecified app even if it has conflicting migrations.
     """
     # Monkeypatch interactive questioner to auto accept
     with mock.patch('django.db.migrations.questioner.input',
                     mock.Mock(return_value='y')):
         out = six.StringIO()
         try:
             with self.temporary_migration_module(
                     app_label="migrated_app") as migration_dir:
                 call_command("makemigrations",
                              "migrated_app",
                              merge=True,
                              interactive=True,
                              stdout=out)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 self.assertFalse(os.path.exists(merge_file))
             self.assertIn("No conflicts detected to merge.",
                           out.getvalue())
         except CommandError:
             self.fail(
                 "Makemigrations fails resolving conflicts in an unspecified app"
             )
Exemple #13
0
 def test_render(self):
     """
     Checks whether the render method calls the _create_choices method
     and returns a result of parent's render method. The _create_choices
     should be called before the parent's render.
     """
     # create a mock for logging calls to determine call order
     call_logger = mock.Mock()
     # attach the _create_choices mock to the logger
     call_logger.attach_mock(self.widget._create_choices, 'create_choices')
     # patch the parent's render method
     with mock.patch.object(Select, 'render', return_value='foo') as render:
         # attach the parent's render mock to the logger
         call_logger.attach_mock(render, 'parent_render')
         # call the render method
         result = widgets.ObjectIdSelect.render(self.widget, 'name',
                                                'value')
     # check whether the method returns the result of the parent's render
     self.assertEqual(result, 'foo')
     # create an expected calls list where the create_choices is called
     # before the parent's render
     expected_calls = [
         mock.call.create_choices(),
         # the parent's render should be called with the same arguments
         mock.call.parent_render('name', 'value', None)
     ]
     # check whether functions has been called in the proper order
     self.assertListEqual(call_logger.mock_calls, expected_calls)
Exemple #14
0
 def side_effect(url, headers, params, verify):
     response_mock = mock.Mock()
     if params['user'] == user.username and params['perm'] in perm_list:
         response_mock.status_code = status.HTTP_200_OK
     else:
         response_mock.status_code = status.HTTP_400_BAD_REQUEST
     return response_mock
Exemple #15
0
 def test_makemigrations_merge_dont_output_dependency_operations(self):
     """
     Makes sure that makemigrations --merge does not output any operations
     from apps that don't belong to a given app.
     """
     # Monkeypatch interactive questioner to auto accept
     with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='N')):
         out = six.StringIO()
         with mock.patch('django.core.management.color.supports_color', lambda *args: False):
             call_command(
                 "makemigrations", "conflicting_app_with_dependencies",
                 merge=True, interactive=True, stdout=out
             )
         val = out.getvalue().lower()
         self.assertIn('merging conflicting_app_with_dependencies\n', val)
         self.assertIn(
             '  branch 0002_conflicting_second\n'
             '    - create model something\n',
             val
         )
         self.assertIn(
             '  branch 0002_second\n'
             '    - delete model tribble\n'
             '    - remove field silly_field from author\n'
             '    - add field rating to author\n'
             '    - create model book\n',
             val
         )
    def test_calls_success_log_on_success(self):
        response = mock.Mock()
        response.json.return_value = {'status': 'ok'}

        with mock.patch('requests.post', return_value=response):
            with mock.patch.object(self.handler, 'log_success') as log_success:
                self.handler.send({})
                log_success.assert_called()
Exemple #17
0
 def test_get_relations_alt_format(self):
     """With SQLite, foreign keys can be added with different syntaxes."""
     with connection.cursor() as cursor:
         cursor.fetchone = mock.Mock(return_value=[
             "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES %s(id));" % Article._meta.db_table
         ])
         relations = connection.introspection.get_relations(cursor, 'mocked_table')
     self.assertEqual(relations, {'art_id': ('id', Article._meta.db_table)})
    def test_calls_fail_log_on_fail(self):
        response = mock.Mock()
        response.raise_for_status.side_effect = requests.RequestException

        with mock.patch('requests.post', return_value=response):
            with mock.patch.object(self.handler, 'log_fail') as log_fail:
                self.handler.send({})
                log_fail.assert_called()
    def test_calls_error_log_on_error(self):
        response = mock.Mock()
        response.raise_for_status.side_effect = ValueError

        with mock.patch('requests.post', return_value=response):
            with mock.patch.object(self.handler, 'log_error') as log_error:
                self.handler.send({})
                log_error.assert_called()
Exemple #20
0
    def test(self):
        destructor_mock = mock.Mock()

        class NullPointerException(Exception):
            pass

        class FakeGeom1(CPointerBase):
            null_ptr_exception_class = NullPointerException

        class FakeGeom2(FakeGeom1):
            ptr_type = ctypes.POINTER(ctypes.c_float)
            destructor = destructor_mock

        fg1 = FakeGeom1()
        fg2 = FakeGeom2()

        # These assignments are OK. None is allowed because it's equivalent
        # to the NULL pointer.
        fg1.ptr = fg1.ptr_type()
        fg1.ptr = None
        fg2.ptr = fg2.ptr_type(ctypes.c_float(5.23))
        fg2.ptr = None

        # Because pointers have been set to NULL, an exception is raised on
        # access. Raising an exception is preferable to a segmentation fault
        # that commonly occurs when a C method is given a NULL reference.
        for fg in (fg1, fg2):
            with self.assertRaises(NullPointerException):
                fg.ptr

        # Anything that's either not None or the acceptable pointer type
        # results in a TypeError when trying to assign it to the `ptr` property.
        # Thus, memory addresses (integers) and pointers of the incorrect type
        # (in `bad_ptrs`) aren't allowed.
        bad_ptrs = (5, ctypes.c_char_p(b'foobar'))
        for bad_ptr in bad_ptrs:
            for fg in (fg1, fg2):
                with self.assertRaisesMessage(TypeError,
                                              'Incompatible pointer type'):
                    fg.ptr = bad_ptr

        # Object can be deleted without a destructor set.
        fg = FakeGeom1()
        fg.ptr = fg.ptr_type(1)
        del fg

        # A NULL pointer isn't passed to the destructor.
        fg = FakeGeom2()
        fg.ptr = None
        del fg
        self.assertFalse(destructor_mock.called)

        # The destructor is called if set.
        fg = FakeGeom2()
        ptr = fg.ptr_type(ctypes.c_float(1.))
        fg.ptr = ptr
        del fg
        destructor_mock.assert_called_with(ptr)
    def test_complete_state_help(self):
        msgr = mock.Mock()
        state = SubscriptionStates(
            self.subscriber(SubscriptionStates.COMPLETE_STATE), msgr)
        state.complete_state_help()

        assert msgr.send.call_count == 1
        self.assertEqual(msgr.send.call_args[0][0][0].contents(),
                         self.read_file("sms_app/assets/eng/error_msg.txt"))
    def test_makes_post_request_with_data(self):
        response = mock.Mock()
        response.json.return_value = {'status': 'ok', 'phone': 'any phone'}

        with mock.patch('requests.post', return_value=response) as post_mock:
            data = {'test_key': 'test_value'}
            self.handler.send(data)

            post_mock.assert_called_with(self.handler.get_url(), data=data)
    def test_lang_selected(self):
        msgr = mock.Mock()
        state = SubscriptionStates(
            self.subscriber(SubscriptionStates.SELECTING_LANG_STATE), msgr)
        state.lang_selected("spa")

        assert msgr.send.call_count == 1
        self.assertEqual(
            msgr.send.call_args[0][0][0].contents(),
            self.read_file("sms_app/assets/spa/confirmation_msg.txt"))
    def test_reselect_language(self):
        msgr = mock.Mock()
        state = SubscriptionStates(
            self.subscriber(SubscriptionStates.COMPLETE_STATE), msgr)
        state.reselect_language()

        assert msgr.send.call_count == 1
        self.assertEqual(
            msgr.send.call_args[0][0][0].contents(),
            self.read_file("sms_app/assets/eng/language_selection_msg.txt"))
    def test_subscribe_help(self):
        msgr = mock.Mock()
        state = SubscriptionStates(
            self.subscriber(SubscriptionStates.UNSUBSCRIBED_STATE), msgr)
        state.subscribe_help()

        assert msgr.send.call_count == 1
        self.assertEqual(
            msgr.send.call_args[0][0][0].contents(),
            self.read_file("sms_app/assets/eng/subscribe_help_msg.txt"))
    def test_connection_error(self, requests_mock):
        perm_code = 'TEST_CODE'
        perm = permissions.CodePermission.decorate(perm_code)()

        exception = None
        try:
            perm.has_permission(self.request, mock.Mock())
        except PermissionDenied as ex:
            exception = ex
        self.assertTrue(exception)
Exemple #27
0
class UtilsTest(TestCase):

    # ------------------------------------------------------------------------------------------------------------------
    def test_generate_password(self):
        password = utils.generate_password()

        self.assertTrue(len(password), utils.PASSWORD_LENGTH)
        self.assertTrue(isinstance(password, str))
        self.assertTrue(password.isalnum())

    # ------------------------------------------------------------------------------------------------------------------
    def test_resize_image(self):
        img_path = os.path.join(TEST_DATA_DIR, 'test_resize_image.png')
        default_size = (400, 500)

        img = Image.open(img_path)
        self.assertEqual((img.width, img.height), default_size)

        utils.resize_image(img_path, 500)

        img = Image.open(img_path)
        self.assertEqual((img.width, img.height), (500, 625))

        utils.resize_image(img_path, default_size[0])

        img = Image.open(img_path)
        self.assertEqual((img.width, img.height), default_size)

    # ------------------------------------------------------------------------------------------------------------------
    @mock.patch('app.utils.requests.post',
                new=mock.Mock(return_value=JsonMock(True)))
    def test_validate_captcha_success(self):
        result = utils.validate_captcha('some_key')
        self.assertTrue(result)

    # ------------------------------------------------------------------------------------------------------------------
    @mock.patch('app.utils.requests.post',
                new=mock.Mock(return_value=JsonMock(False)))
    def test_validate_captcha_fail(self):
        result = utils.validate_captcha('some_key')
        self.assertFalse(result)
    def test_start_subscription(self):
        msgr = mock.Mock()
        state = SubscriptionStates(
            self.subscriber(SubscriptionStates.UNSUBSCRIBED_STATE), msgr)
        state.start_subscription()

        assert msgr.send.call_count == 1
        self.assertEqual(msgr.send.call_args_list[0][0][0][0].contents(),
                         self.read_file("sms_app/assets/eng/welcome_msg.txt"))
        self.assertEqual(
            msgr.send.call_args_list[0][0][0][1].contents(),
            self.read_file("sms_app/assets/eng/language_selection_msg.txt"))
    def test_validation_error(self, requests_mock):
        requests_mock.get.return_value.status_code = status.HTTP_400_BAD_REQUEST

        perm_code = 'TEST_CODE'
        perm = permissions.CodePermission.decorate(perm_code)()

        exception = None
        try:
            perm.has_permission(self.request, mock.Mock())
        except PermissionDenied as ex:
            exception = ex
        self.assertTrue(exception)
Exemple #30
0
 def test_makemigrations_interactive_reject(self):
     """
     Makes sure that makemigrations enters and exits interactive mode properly.
     """
     # Monkeypatch interactive questioner to auto reject
     with mock.patch('django.db.migrations.questioner.input', mock.Mock(return_value='N')):
         try:
             with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
                 call_command("makemigrations", "migrations", merge=True, interactive=True, verbosity=0)
                 merge_file = os.path.join(migration_dir, '0003_merge.py')
                 self.assertFalse(os.path.exists(merge_file))
         except CommandError:
             self.fail("Makemigrations failed while running interactive questioner")