예제 #1
0
def test_get_ids_by_last_name_none():
    mock_store = mockredis.mock_redis_client(strict=True)
    person_index = PersonIndex(mock_store)
    person = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person)
    ids = PersonIndex(mock_store).get_ids_by_last_name('some_other_id')
    assert len(ids) is 0
예제 #2
0
 def setUp(self):
     self.prefix = u'testing.prefix.'
     self.m_redis = mock_redis_client()
     self.m_stats = mock.Mock()
     self.coalescer = coalescer.CoalescingMachine(self.prefix,
                                                  self.m_redis,
                                                  self.m_stats)
예제 #3
0
def test_get_ids_by_last_name_none():
    mock_store = mockredis.mock_redis_client(strict=True)
    person_index = PersonIndex(mock_store)
    person = Person(1, 'first', 'last', 20, 'github_account',
                    '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person)
    ids = PersonIndex(mock_store).get_ids_by_last_name('some_other_id')
    assert len(ids) is 0
예제 #4
0
def test_person():
    mock_store = mockredis.mock_redis_client(strict=True)
    person = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store)
    assert person.id == 1
    assert person.first_name == 'first'
    assert person.last_name == 'last'
    assert person.age == 20
    assert person.github_account == 'github_account'
    assert person.third_grade_graduation == '3rd_grade_grad_date'
예제 #5
0
    def mock_redis_client_singleton(self, connection_pool, *args, **kwargs):

        # A name has to passed into the connection pool, this will make sure
        # that different Redis instances can be mocked
        name = connection_pool.name

        if name not in self.redis_clients:
            self.redis_clients[name] = mock_redis_client()
            self.redis_clients[name].name = name
        return self.redis_clients[name]
예제 #6
0
def items():
    global redis
    if not redis:
        redis = mockredis.mock_redis_client()
    items = {}
    for key in redis.smembers('redwood-tracking-contexts'):
        tracking_context = redis.hget(key, 'tracking_context')
        items[tracking_context] = {}
        mean = float(redis.hget(key, 'sum')) / float(redis.hget(key, 'count'))
        items[tracking_context]['mean'] = mean
    return items
예제 #7
0
def test_get_ids_by_last_name():
    mock_store = mockredis.mock_redis_client(strict=True)
    person_index = PersonIndex(mock_store)
    person1 = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person1)
    person2 = Person(2, 'first', 'last', 30, 'github_account', '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person2)
    ids = person_index.get_ids_by_last_name(person1.last_name)
    assert ids is not None
    assert str(1) in ids
    assert str(2) in ids
예제 #8
0
    def setUp(self):
        web.app.config['TESTING'] = True
        web.app.prefix = self.prefix = 'testing.prefix.'
        web.app.redis = mock_redis_client()

        # Setup some taskIds and timestamps
        web.app.redis.set(self.prefix + 'taskId1' + '.timestamp', 0)
        web.app.redis.set(self.prefix + 'taskId2' + '.timestamp', 5)
        web.app.redis.set(self.prefix + 'taskId3' + '.timestamp', 10)
        web.app.redis.lpush(self.prefix + 'lists.' + 'sample.key.1',
                            'taskId1', 'taskId2', 'taskId3')
        self.app = web.app.test_client()
예제 #9
0
def test_all():
    mock_store = mockredis.mock_redis_client(strict=True)
    person_index = PersonIndex(mock_store)
    person1 = Person(1, 'first', 'last', sys.maxint, 'github_account', '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person1)
    person2 = Person(2, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person2)
    person3 = Person(3, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person3)
    people = person_index.all()
    assert people is not None
    assert next((person for person in people if person.id == str(1)), None) is not None
    assert next((person for person in people if person.id == str(2)), None) is not None
    assert next((person for person in people if person.id == str(3)), None) is not None
예제 #10
0
def app(monkeypatch):
    mock_app = Flask(__name__)
    mock_app.api = Api(mock_app,
                       prefix='/api/v1',
                       errors=api_error_map,
                       catch_all_404s=True)
    mock_app.config['CACHE_TYPE'] = 'simple'
    mock_app.cache = Cache(mock_app)
    mock_app.testing = True
    mock_app.debug = True

    from nextbus.router import setup_router
    setup_router(mock_app)
    mock_app.stats_redis = mock_redis_client()
    mock_app.nextbus_api = NextbusApiClient()

    return mock_app
예제 #11
0
파일: __init__.py 프로젝트: hisdo/lincoln
def create_app(log_level="INFO", config="config.yml"):
    app = Flask(__name__)
    app.secret_key = 'test'
    app.config.from_object(__name__)

    config_vars = yaml.load(open(root + '/config.yml'))
    # inject all the yaml configs
    app.config.update(config_vars)
    db.init_app(app)
    Migrate(app, db)

    # Setup redis
    redis_config = app.config.get('redis_conn', dict(type='live'))
    typ = redis_config.pop('type')
    if typ == "mock_redis":
        from mockredis import mock_redis_client
        app.redis = mock_redis_client()
    else:
        app.redis = Redis(**redis_config)

    del app.logger.handlers[0]
    app.logger.setLevel(logging.NOTSET)
    log_format = logging.Formatter('%(asctime)s [%(name)s] [%(levelname)s]: %(message)s')
    log_level = getattr(logging, str(log_level), app.config.get('log_level', "INFO"))

    logger = logging.getLogger()
    logger.setLevel(log_level)
    handler = logging.StreamHandler(stream=sys.stdout)
    handler.setFormatter(log_format)
    logger.addHandler(handler)

    # Dynamically add all the filters in the filters.py file
    for name, func in inspect.getmembers(filters, inspect.isfunction):
        app.jinja_env.filters[name] = func

    app.rpc_connection = Proxy(
        "http://{0}:{1}@{2}:{3}/"
        .format(app.config['coinserv']['username'],
                app.config['coinserv']['password'],
                app.config['coinserv']['address'],
                app.config['coinserv']['port'])
        )

    from . import views
    app.register_blueprint(views.main)
    return app
예제 #12
0
    def setup(self):
        # Standard redis mock client to be used across multiple patches
        self.redis = mock_redis_client()
        self.redis.publish = mock.MagicMock()

        # Patch redis in the player logic module
        patch = mock.patch(
            'fm.logic.player.redis',
            new_callable=mock.PropertyMock(return_value=self.redis))
        patch.start()
        self.addPatchCleanup(patch)

        # Patch redis in the player views module
        patch = mock.patch(
            'fm.views.player.redis',
            new_callable=mock.PropertyMock(return_value=self.redis))
        patch.start()
        self.addPatchCleanup(patch)
예제 #13
0
def setup():
    import server.db
    import server.tasks
    import server.tasks.data
    from redis import Redis

    logging.Logger.notify = logging.Logger.info
    logging.Logger.alert = logging.Logger.info
    logging.Logger.ops_alert = logging.Logger.info

    HTTPretty.enable()
    HTTPretty.register_uri(httpretty.GET, re.compile('.+'), status=500)
    HTTPretty.register_uri(httpretty.HEAD, re.compile('.+'), status=500)
    HTTPretty.register_uri(httpretty.POST, re.compile('.+'), status=500)

    mock_redis = mock_redis_client()
    mock_redis_queue = Mock(Redis)

    def run_job(job, at_front=False):
        job.perform()

    server.tasks.data_queue.connection = mock_redis_queue
    server.tasks.data_priority_queue.connection = mock_redis_queue
    server.tasks.data_queue.enqueue_job = run_job
    server.tasks.data_priority_queue.enqueue_job = run_job
    server.tasks.predictions_queue.connection = mock_redis_queue
    server.tasks.predictions_queue.enqueue_job = run_job
    server.tasks.parse_queue.connection = mock_redis_queue
    server.tasks.parse_queue.enqueue_job = run_job
    server.tasks.notifications_queue.connection = mock_redis_queue
    server.tasks.notifications_queue.enqueue_job = run_job
    server.tasks.push_queue.connection = mock_redis_queue
    server.tasks.push_queue.enqueue_job = run_job
    server.tasks.images_queue.connection = mock_redis_queue
    server.tasks.images_queue.enqueue_job = run_job
    server.tasks.email_queue.connection = mock_redis_queue
    server.tasks.email_queue.enqueue_job = run_job

    server.db.redis = mock_redis
    server.db.wigo_db.redis = mock_redis
    server.db.wigo_queued_db.redis = mock_redis
    server.db.scheduler.connection = mock_redis_queue
예제 #14
0
def test_all():
    mock_store = mockredis.mock_redis_client(strict=True)
    person_index = PersonIndex(mock_store)
    person1 = Person(1, 'first', 'last', sys.maxint, 'github_account',
                     '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person1)
    person2 = Person(2, 'first', 'last', 20, 'github_account',
                     '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person2)
    person3 = Person(3, 'first', 'last', 20, 'github_account',
                     '3rd_grade_grad_date', mock_store)
    person_index.add_person_to_index(person3)
    people = person_index.all()
    assert people is not None
    assert next((person for person in people if person.id == str(1)),
                None) is not None
    assert next((person for person in people if person.id == str(2)),
                None) is not None
    assert next((person for person in people if person.id == str(3)),
                None) is not None
예제 #15
0
class TestRandom(object):
    @pytest.mark.usefixtures("unauthenticated")
    def test_hit_random_endpoint_as_unauthorized_user(self):
        response = self.client.post(url_for('player.random'))
        assert response.status_code == httplib.UNAUTHORIZED

    def test_data_without_number_of_tracks(self):
        response = self.client.post(url_for('player.random'))
        assert response.status_code == httplib.BAD_REQUEST

    @mock.patch('fm.logic.player.redis', mock_redis_client())
    def test_add_some_tracks_into_queue(self):
        tracks = [TrackFactory(), TrackFactory(), TrackFactory()]
        users = [UserFactory(), UserFactory(), UserFactory()]

        db.session.add_all(tracks + users)
        db.session.commit()

        response = self.client.post(url_for('player.random'),
                                    data=json.dumps({'tracks': 2}))

        assert response.status_code == httplib.CREATED
        assert Queue.length() == 2
예제 #16
0
 def setUp(self):
     self.sample_size = 4
     tables = ['table-%s' % x for x in xrange(self.sample_size)]
     self.camera = Camera('camera')
     self.mock_redis = mock_redis_client()
     self.camera.redis_client = self.mock_redis
예제 #17
0
 def setUp(self):
     self.mock_redis = mock_redis_client()
예제 #18
0
파일: test_store.py 프로젝트: Razumain/pyFF
 def _redis_store(self):
     store = RedisStore()
     store.rc = mockredis.mock_redis_client()
     return store
예제 #19
0
 def setUp(self):
     redisco.connection = mock_redis_client()
     self.app = meetup_slides.app.test_client()
예제 #20
0
                args = ["INSERT OR REPLACE INTO WeRoBot (id, value) VALUES (?,?);", (args[1][0], args[1][1])]
                self.db.execute(*args, **kwargs)
            else:
                self.db.execute(*args, **kwargs)

    def fetchone(self):
        return self.cache_result

    def commit(self):
        return self.db.commit()


@pytest.mark.parametrize("storage", [
    filestorage.FileStorage(),
    mongodbstorage.MongoDBStorage(mongomock.MongoClient().t.t),
    redisstorage.RedisStorage(mockredis.mock_redis_client()),
    sqlitestorage.SQLiteStorage(),
    mysqlstorage.MySQLStorage(MockPyMySQL())
])
def test_storage(storage):
    assert storage.get("喵") == {}
    storage.set("喵", "喵喵")
    assert storage.get("喵") == u"喵喵"
    storage.delete("喵")
    assert storage.get("喵") == {}

    assert storage["榴莲"] == {}
    storage["榴莲"] = "榴莲"
    assert storage["榴莲"] == u"榴莲"
    del storage["榴莲"]
    assert storage["榴莲"] == {}
예제 #21
0
 def test_mock_redis_client(self):
     """
     Test that we can pass kwargs to the Redis mock/patch target.
     """
     self.assertFalse(mock_redis_client(host="localhost", port=6379).strict)
예제 #22
0
 def configure_redis(config):
     typ = config.pop('type')
     if typ == "mock_redis":
         from mockredis import mock_redis_client
         return mock_redis_client()
     return Redis(**config)
예제 #23
0
def test_mock_redis_client():
    """
    Test that we can pass kwargs to the Redis mock/patch target.
    """
    ok_(not mock_redis_client(host="localhost", port=6379).strict)
예제 #24
0
import os
import json
import unittest
import redis
import time
import mockredis
from json import loads
from functools import wraps
from closebus.redis_cache import cache_decorator

redis_cache = mockredis.mock_redis_client()

class RedisTest(unittest.TestCase):
    def test_set(self):
        redis_cache.set('testing', 'hello')
        self.assertEqual(redis_cache.get('testing'), 'hello')

    def test_setex(self):
        redis_cache.setex('testing2', 'hi again', 10)
        time.sleep(1)
        self.assertEqual(redis_cache.get('testing2'), 'hi again')
        self.assertEqual(redis_cache.ttl('testing2') < 10, True)

#     # Mock redis doesn't support automatic expiration
#     def test_decorator_expiration(self):
#         class Temp(object):
#             @cache_decorator(expire=True, ttl_seconds=1)
#             def some_func(self, x=None):
#                 return json.dumps('hello')
#         a = Temp()
#         a.some_func(x='testing')