def setUp(self): self.client = mock_strict_redis_client() self.encoder = Mock() self.encoder.encode = self.reverse_string self.blacklist = Blacklist(self.client, self.encoder) self.poll_texts_key_name = "blacklist:poll_texts:231" self.poll_contacts_key_name = "blacklist:poll_contacts:231"
def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover import mockredis return mockredis.mock_strict_redis_client() # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = caches[config.DEFENDER_REDIS_NAME] except InvalidCacheBackendError: raise KeyError(INVALID_CACHE_ERROR_MSG.format( config.DEFENDER_REDIS_NAME)) # every redis backend implement it own way to get the low level client try: # redis_cache.RedisCache case (django-redis-cache package) return cache.get_master_client() except AttributeError: # django_redis.cache.RedisCache case (django-redis package) return cache.client.get_client(True) else: # pragma: no cover redis_config = parse_redis_url(config.DEFENDER_REDIS_URL) return redis.StrictRedis( host=redis_config.get('HOST'), port=redis_config.get('PORT'), db=redis_config.get('DB'), password=redis_config.get('PASSWORD'))
def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover import mockredis return mockredis.mock_strict_redis_client() # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = caches[config.DEFENDER_REDIS_NAME] except InvalidCacheBackendError: raise KeyError(INVALID_CACHE_ERROR_MSG.format(config.DEFENDER_REDIS_NAME)) # every redis backend implement it own way to get the low level client try: # redis_cache.RedisCache case (django-redis-cache package) return cache.get_master_client() except AttributeError: # django_redis.cache.RedisCache case (django-redis package) return cache.client.get_client(True) else: # pragma: no cover redis_config = parse_redis_url(config.DEFENDER_REDIS_URL) return redis.StrictRedis( host=redis_config.get("HOST"), port=redis_config.get("PORT"), db=redis_config.get("DB"), password=redis_config.get("PASSWORD"), ssl=redis_config.get("SSL"), )
def test_stat_other_user_karma(self): g_mock_redis = mock_strict_redis_client() def _mock_karma_app_factory(*args, **kwargs): karma_app = KarmaApp(*args, **kwargs) karma_app.redis = g_mock_redis return karma_app with patch('rt_karma_bot.KarmaApp', _mock_karma_app_factory): self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': 'alice++', })) self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': '@Alice++', })) response = self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': '/karma @Alice', })) self.assertEqual(response.status_code, 201) response_data = json.loads(response.data.decode('utf-8')) self.assertEqual(response_data['bot'], settings.BOT_NAME) self.assertEqual( response_data['text'], 'Карма пользователя @Alice: 2.', )
def _pre_setup(self): """ Mock requests and redis. """ super()._pre_setup() responses.start() patch('dumblock.redis', mock_strict_redis_client()).start()
async def authorization_flow( self, user=None, console_only=True, refresh_cache=False ): self.user = "******" self.ip = "1.2.3.4" self.groups = ["group1", "group2"] self.contractor = False self.red = mock_strict_redis_client()
def setUp(self): self.rdb = mock_strict_redis_client() if getattr(self, 'CLIENT_PER_TEST', None): self.client = self.app.test_client(use_cookies=True) if getattr(self, 'USE_SESSIONS', None): self.client.__enter__()
class HitCountTest(unittest.TestCase): @patch('hitcount.r', mockredis.mock_strict_redis_client(host='0.0.0.0', port=6379, db=0)) def testOneHit(self): # Increase the hit count for user user1 hitcount.hit("user1") # Ensure that the hit count for user1 is just 1 self.assertEqual(b'1', hitcount.getHit("user1"))
def _init_redis_shards(self): self._shards = {} for shard_num in range(0, self.num_shards()): mock_shard = mockredis.mock_strict_redis_client() # for testing mock_shard.set('shard_num', shard_num) mock_shard.set('shard_name', self.get_shard_name(shard_num)) self._shards[shard_num] = mock_shard
def setUp(self): self.rdb = mock_strict_redis_client() self.img = open('data/img.jpg', 'rb').read() self.cf = ConcreteCamFeeder(self.rdb, 'wilsat', 'archimedes', '', 10, 0) # Start running the greenlet. self.cf.start() self._g = self.cf._g
class TestRedisClient: def test_init(self): with mock.patch('redis.StrictRedis', mock_strict_redis_client): assert RedisClient(settings.REDIS_HOST, settings.REDIS_PORT, settings.REDIS_DB) @mock.patch('redis.StrictRedis', return_value=mock_strict_redis_client()) def test_get_client(self, redis_mock): redis_cli = RedisClient(settings.REDIS_HOST, settings.REDIS_PORT, settings.REDIS_DB) client = redis_cli.get_client() assert isinstance(client, MockRedis)
class HitCountTest(unittest.TestCase): @patch('hitcount.r', mockredis.mock_strict_redis_client(host="0.0.0.0", port=6379, db=0)) def testOneHit(self): hitcount.hit("user1") self.assertEqual(b'1', hitcount.gethit("user1")) @patch('hitcount.r', mockredis.mock_strict_redis_client(host="0.0.0.0", port=6379, db=0)) def testTWOHits(self): hitcount.hit("user1") hitcount.hit("user1") self.assertEqual(b'2', hitcount.gethit("user1")) @patch('hitcount.r', mockredis.mock_strict_redis_client(host="0.0.0.0", port=6379, db=0)) def testThreeHits(self): hitcount.hit("user1") hitcount.hit("user1") hitcount.hit("user1") self.assertEqual(b'3', hitcount.gethit("user1"))
def setup_dbconnector(self, file_name, suffix): ''' Set up the DBconnector instance by mocking its redis client and load the desired port_name_map ''' self.db_connector = dbconnector.DBConnector() ifdb_id = dbconnector.DBConnector.get_dbid(snmpsubagent.MyAgent.IF_DB) ifdb_client = mock_strict_redis_client(host=dbconnector.DBConnector.LOCAL_HOST, port=dbconnector.DBConnector.REDIS_PORT, db=ifdb_id) # load port name map to ifdb_client self.load_port_name_map(ifdb_client, file_name, suffix) self.load_interfaces(ifdb_client, suffix) lldpdb_id = dbconnector.DBConnector.get_dbid(snmpsubagent.MyAgent.LLDP_DB) lldpdb_client = mock_strict_redis_client(host=dbconnector.DBConnector.LOCAL_HOST, port=dbconnector.DBConnector.REDIS_PORT, db=lldpdb_id) self.db_connector.redis_client = {snmpsubagent.MyAgent.IF_DB: ifdb_client, snmpsubagent.MyAgent.LLDP_DB: lldpdb_client}
def test_decr_karma(self): g_mock_redis = mock_strict_redis_client() def _mock_karma_app_factory(*args, **kwargs): karma_app = KarmaApp(*args, **kwargs) karma_app.redis = g_mock_redis return karma_app with patch('rt_karma_bot.KarmaApp', _mock_karma_app_factory): response = self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': 'Alice--', })) self.assertEqual(response.status_code, 201) response_data = json.loads(response.data.decode('utf-8')) self.assertEqual(response_data['bot'], settings.BOT_NAME) self.assertEqual( response_data['text'], 'Карма пользователя @Alice уменьшена (текущее значение: -1).') response = self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': 'alice--', })) response_data = json.loads(response.data.decode('utf-8')) self.assertEqual( response_data['text'], 'Карма пользователя @alice уменьшена (текущее значение: -2).') response = self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': 'Alice--', })) response_data = json.loads(response.data.decode('utf-8')) self.assertEqual( response_data['text'], 'Вы можете менять карму пользователю не чаще раза в сутки.', ) response = self.app.post('/event', data=json.dumps({ 'username': '******', 'display_name': 'Test', 'text': 'joe--', })) response_data = json.loads(response.data.decode('utf-8')) self.assertEqual(response_data['text'], 'Вы не можете изменять свою карму!')
def setUp(self): self.rdb = mock_strict_redis_client() self.img = open('data/img.jpg', 'rb').read() self.cf = MPEGFeeder(self.rdb, 'archimedes', 'http://fake.com/video.mjpeg', 'avconv') # We mock the subprocess.Popen call to provide our own test stream self.popen_patcher = patch('subprocess.Popen') self.popen_mock = self.popen_patcher.start() self.addCleanup(self.popen_patcher.stop) self.test_file = open("data/stream.mpeg", "rb") type(self.popen_mock.return_value).stdout = PropertyMock( return_value=self.test_file)
def setUp(self): self.rdb = mock_strict_redis_client() self.img = open('data/img.jpg', 'rb').read() self.cf = H264ToFramesFeeder(self.rdb, 'wilsat', 'archimedes', 'http://fake.com/video.h264', 'ffmpeg') # We mock the subprocess.Popen call to provide our own test stream self.popen_patcher = patch('feeder.h264_to_frames.subprocess.Popen') self.popen_mock = self.popen_patcher.start() self.addCleanup(self.popen_patcher.stop) self.test_file = open("data/stream.h264", "rb") type(self.popen_mock.return_value).stdout = PropertyMock( return_value=self.test_file)
def setUp(self): self.rdb = mock_strict_redis_client() self.img = open('data/img.jpg', 'rb').read() self.cf = ImageRefreshCamFeeder(self.rdb, 'wilsat', 'archimedes', 'http://fake.com/image.jpg', 10, 0) # We mock erequests.async.get calls. self.get_patcher = patch('requests.Session.get') self.get_mock = self.get_patcher.start() self.addCleanup(self.get_patcher.stop) fixed_response = requests.Response() fixed_response.status_code = 404 fixed_response.raw = io.BytesIO(b"1234567890"*12) self.get_mock.return_value = fixed_response
def setUp(self): self.rdb = mock_strict_redis_client() self.cf = MJPEGCamFeeder(self.rdb, 'wilsat', 'archimedes', 'http://fake.com/image.mjpg', 10, 0) # We mock requests.get calls. self.get_patcher = patch('requests.get') self.get_mock = self.get_patcher.start() self.addCleanup(self.get_patcher.stop) fixed_response = requests.Response() fixed_response.status_code = 200 fixed_response.headers[ 'content-type'] = 'multipart/x-mixed-replace;boundary=--video boundary--' fixed_response.raw = io.FileIO('data/example.mjpeg', 'rb') self.get_mock.return_value = fixed_response
def mock_client(): mock_client = mock_strict_redis_client() # Adding a couple of methods we use that mockredis doesn't support yet. def scan_iter_patch(match=None, count=100): match = str(match).replace('*', '') return filter(lambda k: k.startswith(match), mock_client.keys()) mock_client.scan_iter = scan_iter_patch mock_client.reset = lambda: True def zscan_iter_patch(key, match=None): match = str(match).replace('*', '') return filter(lambda k: k.startswith(match), mock_client.zrange(key, 0, -1)) mock_client.zscan_iter = zscan_iter_patch return mock_client
def mock_client(): mock_client = mock_strict_redis_client() # Adding a couple of methods we use that mockredis doesn't support yet. def scan_iter_patch(match=None, count=100): match = str(match).replace("*", "") return filter(lambda k: k.startswith(match), mock_client.keys()) mock_client.scan_iter = scan_iter_patch mock_client.reset = lambda: True def zscan_iter_patch(key, match=None): match = str(match).replace("*", "") return filter(lambda k: k.startswith(match), mock_client.zrange(key, 0, -1)) mock_client.zscan_iter = zscan_iter_patch return mock_client
def setUp(self): """ Test that we can grab a single frame and that apprently it returns what we expect. :return: """ self.rdb = mock_strict_redis_client() self._img_file = open('data/img.jpg', 'rb') self.img = self._img_file.read() self.cf = ImageRefreshCamFeeder(self.rdb, 'wilsat', 'archimedes', 'http://fake.com/image.jpg', 10, 0) # We mock requests.get calls. self.get_patcher = patch('requests.Session.get') self.get_mock = self.get_patcher.start() self.addCleanup(self.get_patcher.stop) # Ensure that the request returns fixed_response = requests.Response() fixed_response.status_code = 200 fixed_response.raw = io.BytesIO(b"1234567890"*12) self.get_mock.return_value = fixed_response
from werkzeug.urls import url_unquote_plus NO_SSL = os.environ.get('NO_SSL', False) TOKEN_SEPARATOR = '~' # Initialize Flask Application app = Flask(__name__) if os.environ.get('DEBUG'): app.debug = True app.secret_key = os.environ.get('SECRET_KEY', 'Secret Key') app.config.update(dict(STATIC_URL=os.environ.get('STATIC_URL', 'static'))) # Initialize Redis if os.environ.get('MOCK_REDIS'): from mockredis import mock_strict_redis_client redis_client = mock_strict_redis_client() elif os.environ.get('REDIS_URL'): redis_client = redis.StrictRedis.from_url(os.environ.get('REDIS_URL')) else: redis_host = os.environ.get('REDIS_HOST', 'localhost') redis_port = os.environ.get('REDIS_PORT', 6379) redis_db = os.environ.get('SNAPPASS_REDIS_DB', 0) redis_client = redis.StrictRedis(host=redis_host, port=redis_port, db=redis_db) REDIS_PREFIX = os.environ.get('REDIS_PREFIX', 'snappass') TIME_CONVERSION = {'week': 604800, 'day': 86400, 'hour': 3600} def check_redis_alive(fn):
def fake_get_redis(): with patch("zconnect.tasks.get_redis", return_value=mock_strict_redis_client()), \ patch("zconnect.util.rate_limiter.get_redis", return_value=mock_strict_redis_client()): yield
class TestCommentDelete: @pytest.fixture def user_data(self): return { 'auth_user': { 'email': '*****@*****.**', 'username': '******', } } @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_comment_delete(self, redis_mock, client, comment_factory, user_data): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) response = client.delete(url, data=json.dumps(user_data), content_type='application/json') assert response.status_code == status.HTTP_204_NO_CONTENT @pytest.mark.django_db def test_no_data_send(self, client, comment_factory): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) response = client.delete(url) assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.json() == {'error': 'JSON decode error'} @pytest.mark.django_db def test_user_is_required(self, client, comment_factory): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) response = client.delete(url, data=json.dumps({'content': '1'}), content_type='application/json') assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.json() == {'auth_user': ['This field is required.']} @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_comment_delete_do_not_delete_from_database( self, redis_mock, client, comment_factory, user_data): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) client.delete(url, data=json.dumps(user_data), content_type='application/json') comment.refresh_from_db() assert comment.is_deleted is True @pytest.mark.django_db def test_comment_delete_do_not_delete_parent_comment( self, client, comment_factory, user_data): comment = comment_factory.create(parent__parent=None) url = reverse('comments:delete', kwargs={'pk': comment.parent.pk}) response = client.delete(url, data=json.dumps(user_data), content_type='application/json') assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.json() == {'error': 'Could not delete parent comment'} @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_create_history_record_on_comment_delete(self, redis_mock, client, comment_factory, user_data): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) client.delete(url, data=json.dumps(user_data), content_type='application/json') history = CommentHistory.objects.get(comment_id=comment.pk) assert history.action == CommentHistory.DELETED assert history.content == comment.content assert history.user.username == user_data['auth_user']['username'] @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_send_notification_on_comment_delete(self, redis_mock, client, comment_factory, user_data): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) client.delete(url, data=json.dumps(user_data), content_type='application/json') assert redis_mock.called @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_same_user_can_delete_comment_more_than_once( self, redis_mock, client, comment_factory, user_data): for _ in range(2): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) response = client.delete(url, data=json.dumps(user_data), content_type='application/json') assert response.status_code == status.HTTP_204_NO_CONTENT @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_ignore_user_email_if_user_already_exists(self, redis_mock, client, comment_factory, user_data): comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) response = client.delete(url, data=json.dumps(user_data), content_type='application/json') assert response.status_code == status.HTTP_204_NO_CONTENT user_data['auth_user']['email'] = '*****@*****.**' comment = comment_factory.create(parent=None) url = reverse('comments:delete', kwargs={'pk': comment.pk}) response = client.delete(url, data=json.dumps(user_data), content_type='application/json') assert response.status_code == status.HTTP_204_NO_CONTENT
class TestCommentUpdate: @pytest.fixture def update_data(self): return { 'comment': { 'content': 'Edited!', }, 'auth_user': { 'email': '*****@*****.**', 'username': '******', }, } @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_comment_update(self, redis_mock, client, comment_factory, update_data): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) response = client.patch(url, data=json.dumps(update_data), content_type='application/json') assert response.status_code == status.HTTP_200_OK @pytest.mark.django_db @pytest.mark.parametrize('key', ['comment', 'auth_user']) def test_comment_and_user_is_required(self, client, comment_factory, update_data, key): update_data.pop(key) comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) response = client.patch(url, data=json.dumps(update_data), content_type='application/json') assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.json() == { 'non_field_errors': [f'`{key}` field is required'] } @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_comment_update_updates_only_content(self, redis_mock, client, comment_factory): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) data = { 'comment': { 'content_type_id': 10, 'object_id': 10, 'content': 'Edited!Again', 'author': { 'email': '*****@*****.**', 'username': '******', }, }, 'auth_user': { 'email': '*****@*****.**', 'username': '******', }, } client.patch(url, data=json.dumps(data), content_type='application/json') comment.refresh_from_db() assert comment.content_type_id == 1 assert comment.object_id == 1 assert comment.content == 'Edited!Again' assert comment.author.username == comment.author.username assert comment.author.email == comment.author.email @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_create_history_record_on_comment_update(self, redis_mock, client, comment_factory, update_data): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) response = client.patch(url, data=json.dumps(update_data), content_type='application/json') content = response.json() comment_id = content['comment']['id'] history = CommentHistory.objects.get(comment_id=comment_id) assert history.action == CommentHistory.UPDATED assert history.content == update_data['comment']['content'] assert history.user.username == update_data['auth_user']['username'] @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_send_notification_on_comment_update(self, redis_mock, client, comment_factory, update_data): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) client.patch(url, data=json.dumps(update_data), content_type='application/json') assert redis_mock.called @pytest.mark.django_db def test_comment_update_put_is_not_allowed(self, client, comment_factory, update_data): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) response = client.put(url, data=json.dumps(update_data), content_type='application/json') assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_same_user_can_update_comment_more_than_once( self, redis_mock, client, comment_factory, update_data): for _ in range(2): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) response = client.patch(url, data=json.dumps(update_data), content_type='application/json') assert response.status_code == status.HTTP_200_OK @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_ignore_user_email_if_user_already_exists(self, redis_mock, client, comment_factory, update_data): comment = comment_factory.create(parent=None) url = reverse('comments:update', kwargs={'pk': comment.pk}) client.patch(url, data=json.dumps(update_data), content_type='application/json') old_email = update_data['auth_user']['email'] update_data['auth_user']['email'] = '*****@*****.**' response = client.patch(url, data=json.dumps(update_data), content_type='application/json') assert response.status_code == status.HTTP_200_OK assert response.json()['auth_user']['email'] == old_email
class TestCommentCreate: url = reverse('comments:create') @pytest.fixture def comment_data(self): return { 'comment': { 'content_type_id': 1, 'object_id': 1, 'content': 'Really good comment', }, 'auth_user': { 'email': '*****@*****.**', 'username': '******', }, } @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_comment_create(self, redis_mock, client, comment_data): response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == status.HTTP_201_CREATED @pytest.mark.django_db @pytest.mark.parametrize('key', ['comment', 'auth_user']) def test_comment_and_user_is_required(self, client, comment_data, key): comment_data.pop(key) response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.json() == {key: ['This field is required.']} @pytest.mark.django_db def test_create_comment_with_non_existing_parent(self, client, comment_data): comment_data['comment']['parent'] = -1 response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.json() == { 'comment': { 'parent': ['Invalid pk "-1" - object does not exist.'] } } @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_create_reply_to_comment(self, redis_mock, client, comment_factory, comment_data): comment = comment_factory.create(parent=None) comment_data['comment'].update({ 'content_type_id': comment.content_type_id, 'object_id': comment.object_id, 'parent': comment.pk }) response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == status.HTTP_201_CREATED @pytest.mark.django_db @pytest.mark.parametrize( ['content_type_id', 'object_id', 'expected_status'], [ (1, 10, status.HTTP_400_BAD_REQUEST), (10, 1, status.HTTP_400_BAD_REQUEST), (10, 10, status.HTTP_400_BAD_REQUEST), ]) def test_create_reply_to_comment_with_different_thread( self, client, comment_factory, comment_data, content_type_id, object_id, expected_status): comment = comment_factory.create(parent=None) comment_data['comment'].update({ 'content_type_id': content_type_id, 'object_id': object_id, 'parent': comment.pk }) response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == expected_status @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_create_history_record_on_comment_create(self, redis_mock, client, comment_data): response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') content = response.json() comment_id = content['comment']['id'] history = CommentHistory.objects.get(comment_id=comment_id) assert history.action == CommentHistory.CREATED assert history.content == content['comment']['content'] assert history.user.username == comment_data['auth_user']['username'] @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_send_notification_on_comment_create(self, redis_mock, client, comment_data): client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert redis_mock.called @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_same_user_can_create_comment_more_than_once( self, redis_mock, client, comment_data): for _ in range(2): response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == status.HTTP_201_CREATED @pytest.mark.django_db @mock.patch.object(RedisClient, 'get_client', return_value=mock_strict_redis_client()) def test_ignore_user_email_if_user_already_exists(self, redis_mock, client, comment_data): client.post(self.url, data=json.dumps(comment_data), content_type='application/json') old_email = comment_data['auth_user']['email'] comment_data['auth_user']['email'] = '*****@*****.**' response = client.post(self.url, data=json.dumps(comment_data), content_type='application/json') assert response.status_code == status.HTTP_201_CREATED assert response.json()['auth_user']['email'] == old_email
import unittest from unittest.mock import patch import mockredis import hitcount @patch('hitcount.r',mockredis.mock_strict_redis_client(host='0.0.0.0',port=6379,db=0)) class HitCountTest(unittest.TestCase): def testOneHit(self): hitcount.hit("user1") self.assertEqual(b'1',hitcount.getHit("user1")) if __name__ == '__main__': unittest.main()
def setUp(self): self.client = mock_strict_redis_client() self.blacklist = Blacklist(self.client, Encoder())
import mockredis import redis try: import urlparse except ImportError: # pragma: no cover import urllib.parse as urlparse # pragma: no cover # Python3 # pylint: disable=import-error,no-name-in-module,line-too-long from . import config # Register database schemes in URLs. urlparse.uses_netloc.append("redis") MOCKED_REDIS = mockredis.mock_strict_redis_client() def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover return MOCKED_REDIS # pragma: no cover else: # pragma: no cover redis_config = parse_redis_url(config.DEFENDER_REDIS_URL) return redis.StrictRedis( host=redis_config.get('HOST'), port=redis_config.get('PORT'), db=redis_config.get('DB'), password=redis_config.get('PASSWORD')) def parse_redis_url(url): """Parses a redis URL."""
def fake_get_redis(): with patch("zconnect.tasks.get_redis", return_value=mock_strict_redis_client()): yield
def setUp(self): self.rdb = mock_strict_redis_client() self.img = open('data/img.jpg', 'rb').read() self.cf = ImageRefreshCamFeeder(self.rdb, 'wilsat', 'archimedes', 'http://fake.com/image.jpg', 10, 0)
def setUp(self): self.client = mock_strict_redis_client() self.whitelist = Whitelist(self.client, Encoder())
from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError import mockredis import redis try: import urlparse except ImportError: # pragma: no cover import urllib.parse as urlparse # pragma: no cover # Python3 # pylint: disable=import-error,no-name-in-module,line-too-long from . import config # Register database schemes in URLs. urlparse.uses_netloc.append("redis") MOCKED_REDIS = mockredis.mock_strict_redis_client() INVALID_CACHE_ERROR_MSG = 'The cache {} was not found on the django cache' \ ' settings.' def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover return MOCKED_REDIS # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = caches[config.DEFENDER_REDIS_NAME] except InvalidCacheBackendError: raise KeyError(INVALID_CACHE_ERROR_MSG.format( config.DEFENDER_REDIS_NAME)) # every redis backend implement it own way to get the low level client
def setUp(self): self.client = mock_strict_redis_client() self.cache = BlacklistCache(self.client)
from collections import namedtuple from mockredis import mock_strict_redis_client redis_db = mock_strict_redis_client( host="0.0.0.0", port=6379, db=0, decode_responses=True, ) # A simple mock we can populate with a textual representation of the user's profile HTML ProfileMock = namedtuple("ProfileMock", "text")
def setUp(self): self.client = mock_strict_redis_client() self.blacklist = Blacklist(self.client, Encoder()) self.contact_filter = IncomingContactFilter(self.blacklist, self.RANDOM_CONTACT)
from quart_cors import cors from .config import config, load_config logging.basicConfig(level=logging.DEBUG) app = Quart(__name__) for key in config.keys(): app.config[key] = config[key] app = cors(app, allow_headers=['X-Requested-With'], allow_origin=app.config['ALLOW_ORIGIN']) load_config() if "pytest" in sys.modules: from mockredis import mock_strict_redis_client store = RedisStore(mock_strict_redis_client()) else: store = RedisStore(redis.StrictRedis(host=app.config['REDIS_HOST'])) prefixed_store = PrefixDecorator('sessions_', store) KVSessionExtension(prefixed_store, app) from .gateway import proxy from .auth import web from .auth.gitlab_auth import gitlab_login, gitlab_get_tokens, gitlab_logout from .auth.jupyterhub_auth import jupyterhub_login, jupyterhub_get_tokens, jupyterhub_logout
def get_redis(self): if self.__redis is None: self.__redis = mockredis.mock_strict_redis_client() return self.__redis
def setUp(self): self.client = mock_strict_redis_client() self.cache = StepsCache(self.client, "username", "password", "http://random/url", "ureport-registration-steps")
def setUp(self): self.rdb = mock_strict_redis_client() self.img = open('data/img.jpg', 'rb').read() self.cf = CamFeeder(self.rdb, 'wilsat', 'archimedes', '', 10, 0)
import mockredis import redis try: import urlparse except ImportError: # pragma: no cover import urllib.parse as urlparse # pragma: no cover # Python3 # pylint: disable=import-error,no-name-in-module,line-too-long from . import config # Register database schemes in URLs. urlparse.uses_netloc.append("redis") mocked_redis = mockredis.mock_strict_redis_client() def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover return mocked_redis # pragma: no cover else: # pragma: no cover if config.DEFENDER_REDIS_URL: redis_config = parse_redis_url(config.DEFENDER_REDIS_URL) else: redis_config = { "DB": 0, "PASSWORD": None, "HOST": config.REDIS_HOST, "PORT": 6379, } return redis.StrictRedis(host=redis_config.get('HOST'), port=redis_config.get('PORT'),
def test_mock_strict_redis_client(): """ Test that we can pass kwargs to the StrictRedis mock/patch target. """ ok_(mock_strict_redis_client(host="localhost", port=6379).strict)
def pubsub_conn(): """Create a connection for the Redis PubSub.""" p_conn = mockredis.mock_strict_redis_client(host='localhost', port=6379, db=5) return p_conn