Example #1
0
class MoxTestBase(object):
    def setup_method(self, method):
        self.mox = Mox()

    def teardown_method(self, method):
        self.mox.UnsetStubs()
        self.mox.VerifyAll()
Example #2
0
def test_terrain_import_exception():
    "lettuce error tries to import "

    string = 'Lettuce has tried to load the conventional environment ' \
        'module "terrain"\nbut it has errors, check its contents and ' \
        'try to run lettuce again.\n\nOriginal traceback below:\n\n'

    mox = Mox()

    mox.StubOutWithMock(lettuce.fs, 'FileSystem')
    mox.StubOutWithMock(lettuce.exceptions, 'traceback')
    mox.StubOutWithMock(lettuce.sys, 'stderr')

    exc = Exception('foo bar')
    lettuce.fs.FileSystem._import('terrain').AndRaise(exc)
    lettuce.exceptions.traceback.format_exc(exc). \
        AndReturn('I AM THE TRACEBACK FOR IMPORT ERROR')

    lettuce.sys.stderr.write(string)
    lettuce.sys.stderr.write('I AM THE TRACEBACK FOR IMPORT ERROR')

    mox.ReplayAll()

    try:
        reload(lettuce)
    except SystemExit:
        mox.VerifyAll()

    finally:
        mox.UnsetStubs()
Example #3
0
class TwitterFriendHandlerTest(TestCase):
    def setUp(self):
        self.m = Mox()

    def tearDown(self):
        self.m.UnsetStubs()

    def test_put_friend(self):
        request, response = new_mock_request_response(self.m)
        self.m.StubOutWithMock(TwitterConnector, "new_api")

        api = _create_api(self.m)
        TwitterConnector.new_api().AndReturn(api)

        username = "******"
        api.CreateFriendship(username)
        response.set_status(204)

        handler = TwitterFriendHandler()
        handler.initialize(request, response)
        set_api_user(self.m)

        self.m.ReplayAll()
        handler.put(username)
        self.m.VerifyAll()
class BlogCommentTest(TestCase):

    def setUp(self):
        initialize(rdb_path='sqlite:///:memory:')
        self.mocker = Mox()
        model = KMBlogComment()
        model.save() # id = 1のデータを登録


    def tearDown(self):
        pass


    def test_set_data(self):
        model = KMBlogComment()
        test_article_id = 'test_article_id'
        test_comment = 'test_comment'
        data = self.mocker.CreateMock(KMData)
        data.get_request_parameter('article_id', default='', decode=True).AndReturn(test_article_id)
        data.get_request_parameter('comment', default='', decode=True).AndReturn(test_comment)
        self.mocker.ReplayAll()
        model.set_data(data);
        # KMDataで指定した値が設定されること
        eq_(model.article_id, test_article_id)
        eq_(model.comment, test_comment)
        eq_(model.error, None)
        self.mocker.UnsetStubs()
        self.mocker.VerifyAll()
Example #5
0
class StatsHandlerTest(TestCase):
    
    def setUp(self):
        self.m = Mox()
        
    def tearDown(self):
        self.m.UnsetStubs()
    
    def test_get(self):
        request, response = new_mock_request_response(self.m)
        self.m.StubOutWithMock(ArtifactSourceAccessor, "find_artifact_counts")
        self.m.StubOutWithMock(ArtifactSourceAccessor, "find_artifact_counts_newer")
        self.m.StubOutWithMock(memcache, "get_stats")
        self.m.StubOutWithMock(ConfigurationAccessor, "get_or_create")
        
        ArtifactSourceAccessor.find_artifact_counts().AndReturn({})
        ArtifactSourceAccessor.find_artifact_counts_newer(IgnoreArg()).AndReturn({})
        memcache.get_stats().AndReturn({})
        
        # token = "oauth_token_secret=hi&oauth_token=hi"
        # config = MockEntity(key_name="hi", twitter_oauth_enabled=True, twitter_access_token=token, twitter_read_only=False)
        # ConfigurationAccessor.get_or_create().AndReturn(config)

        api = new_mock_twitter_api(self.m)
        api.GetUserTimeline(count=IgnoreArg()).AndReturn(())
        api.GetDirectMessages(since=IgnoreArg()).AndReturn(())
        api.GetReplies(since=IgnoreArg()).AndReturn(())
                    
        handler = StatsHandler()
        handler.initialize(request, response)
        
        self.m.ReplayAll()
        handler.get()
        self.m.VerifyAll()
Example #6
0
def test_extract_zip_verbose():
    mox = Mox()
    sys.stdout = StringIO()
    class MyFs(io.FileSystem):
        stack = []
        abspath = mox.CreateMockAnything()
        pushd = mox.CreateMockAnything()
        popd = mox.CreateMockAnything()
        open_raw = mox.CreateMockAnything()
        mkdir = mox.CreateMockAnything()

    mox.StubOutWithMock(io, 'zipfile')

    filename = 'modafoca.zip'
    base_path = '../to/project'
    full_path = '/full/path/to/project'

    MyFs.abspath(base_path).AndReturn(full_path)
    MyFs.pushd(full_path)

    zip_mock = mox.CreateMockAnything()

    io.zipfile.ZipFile(filename).AndReturn(zip_mock)

    file_list = [
        'settings.yml',
        'app',
        'app/controllers.py'
    ]
    zip_mock.namelist().AndReturn(file_list)
    zip_mock.read('settings.yml').AndReturn('settings.yml content')
    zip_mock.read('app/controllers.py').AndReturn('controllers.py content')

    file_mock1 = mox.CreateMockAnything()
    MyFs.open_raw('settings.yml', 'w').AndReturn(file_mock1)
    file_mock1.write('settings.yml content')
    file_mock1.close()

    MyFs.open_raw('app', 'w').AndRaise(IOError('it is a directory, dumb ass!'))
    MyFs.mkdir('app')

    file_mock2 = mox.CreateMockAnything()
    MyFs.open_raw('app/controllers.py', 'w').AndReturn(file_mock2)
    file_mock2.write('controllers.py content')
    file_mock2.close()

    MyFs.popd()

    mox.ReplayAll()
    try:
        MyFs.extract_zip('modafoca.zip', base_path, verbose=True)
        assert_equals(sys.stdout.getvalue(),
                      'Extracting files to /full/path/to/project\n  ' \
                      '-> Unpacking settings.yml\n  -> Unpacking app' \
                      '\n---> Creating directory app\n  -> Unpacking' \
                      ' app/controllers.py\n')
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
        sys.stdout = sys.__stdout__
Example #7
0
class TwitterUserHandlerTest(TestCase):
    def setUp(self):
        self.m = Mox()

    def tearDown(self):
        self.m.UnsetStubs()

    def test_put_friend(self):
        request, response = new_mock_request_response(self.m)
        self.m.StubOutWithMock(TwitterConnector, "new_api")

        api = _create_api(self.m)
        TwitterConnector.new_api().AndReturn(api)

        username = "******"
        api.GetUser(username).AndReturn(
            Mock(name="hi",
                 screen_name=username,
                 url="hi",
                 statuses_count=1,
                 followers_count=1,
                 friends_count=1))

        handler = TwitterUserHandler()
        handler.initialize(request, response)
        set_api_user(self.m)

        self.m.ReplayAll()
        handler.get(username)
        self.m.VerifyAll()
def test_can_be_get_object():
    mox = Mox()

    class MockObject(object):
        pass

    mockobject = MockObject()
    key = "should-be-key"
    value = mockobject

    mox.StubOutWithMock(backend, 'memcache', use_mock_anything=True)

    cache_mock = mox.CreateMockAnything()
    cache_mock.get(key).AndReturn(value)

    backend.memcache.Client(["localhost:11211"]).AndReturn(cache_mock)

    mox.ReplayAll()
    try:
        memcache = backend.MemcachedClass(server=["localhost:11211"],
                                          timeout=30)
        assert memcache.get(key) == value

        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #9
0
def test_class_loader_loads_from_file():
    mox = Mox()

    mox.StubOutWithMock(io, 'os')
    mox.StubOutWithMock(io.sys, 'path')
    io.os.path = mox.CreateMockAnything()
    io.__import__ = mox.CreateMockAnything()

    class_dir = '/full/path/to/module/or'
    class_file = 'file.py'
    class_path = '%s/%s' % (class_dir, class_file)

    io.os.path.isdir(class_path).AndReturn(False)

    io.os.path.split(class_path).AndReturn((class_dir, class_file))
    io.os.path.splitext(class_file).AndReturn(('file', '.py'))

    io.sys.path.append(class_dir)
    io.sys.path.pop()
    module_mock = mox.CreateMockAnything()
    module_mock.ClassIWantToLoad = 'should_be_expected_class'
    io.__import__('file').AndReturn(module_mock)

    mox.ReplayAll()

    try:
        cl = io.ClassLoader(class_path)
        assert_equals(cl.load('ClassIWantToLoad'), 'should_be_expected_class')
        mox.VerifyAll()
    finally:
        io.__import__ = __import__
        mox.UnsetStubs()
Example #10
0
def test_go_through_main_run():
    mox = Mox()
    bobby = bob.Bob
    old_sys = bob.sys

    mock_parser = mox.CreateMockAnything()
    file_system = mox.CreateMockAnything()

    bob.sys = mox.CreateMockAnything()

    bob_mock = mox.CreateMockAnything()
    bob_instance_mock = mox.CreateMockAnything()
    bob_instance_mock.run = mox.CreateMockAnything()

    bob_instance_mock.run().AndReturn(0)
    bob_mock.__call__(parser=mock_parser,
                      fs=file_system).AndReturn(bob_instance_mock)
    bob.sys.exit(0)
    bob.Bob = bob_mock
    mox.ReplayAll()

    try:
        got = bob.run(parser=mock_parser, fs=file_system)
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
        bob.Bob = bobby
        bob.sys = old_sys
Example #11
0
def test_locate_recursive():
    "FileSystem.locate recursive"
    mox = Mox()

    base_path = '../to/project'
    full_path = '/full/path/to/project'

    class MyFs(io.FileSystem):
        stack = []
        abspath = mox.CreateMockAnything()
        walk = mox.CreateMockAnything()

    io.glob('%s/*match*.py' % full_path)
    MyFs.abspath(base_path).AndReturn(full_path)

    walk_list = [(None, None, ['file1.py', 'file2.jpg']),
                 (None, None, ['path1/file3.png', 'path1/file4.html'])]
    MyFs.walk(full_path).AndReturn(walk_list)

    mox.ReplayAll()
    try:
        MyFs.locate(base_path, '*match*.py', recursive=True)
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #12
0
class ArtifactSourceAccessorTest(TestCase):
    def setUp(self):
        self.m = Mox()

    def tearDown(self):
        self.m.UnsetStubs()

    def test_delete_by_name_missing_source(self):
        self.m.StubOutWithMock(ArtifactSource, "get_by_name")

        name = "mhawthorne"
        ArtifactSource.get_by_name(name)

        self.m.ReplayAll()
        self.assertRaises(NotFoundException,
                          ArtifactSourceAccessor.delete_by_name, name)
        self.m.VerifyAll()

    def test_delete_by_name_deletes_source_with_referencing_feed(self):
        # self.m.StubOutWithMock(antonym_model, 'ArtifactSource')
        self.m.StubOutWithMock(ArtifactSource, "get_by_name")
        self.m.StubOutWithMock(FeedAccessor, "get_by_source_name")

        name = "mhawthorne"
        source = MockEntity(key_name=name)
        ArtifactSource.get_by_name(name).AndReturn(source)
        FeedAccessor.get_by_source_name(name, return_none=True).AndReturn(
            MockEntity(key=name, url="http://real.ly"))

        self.m.ReplayAll()
        self.assertRaises(ConflictingDataException,
                          ArtifactSourceAccessor.delete_by_name, name)
        self.m.VerifyAll()

    def test_delete_by_name_deletes_source_with_no_referencing_feed(self):
        self.m.StubOutWithMock(ArtifactSource, "get_by_name")
        self.m.StubOutWithMock(FeedAccessor, "get_by_source_name")
        self.m.StubOutWithMock(ArtifactInfo, "find_by_source")
        self.m.StubOutWithMock(ArtifactContent, "find_by_source")
        self.m.StubOutWithMock(db, "delete")
        self.m.StubOutWithMock(memcache, "delete")

        name = "mhawthorne"
        source = MockEntity(key_name=name)
        ArtifactSource.get_by_name(name).AndReturn(source)
        FeedAccessor.get_by_source_name(name, return_none=True)
        ArtifactInfo.find_by_source(source, keys_only=True).AndReturn(
            MockQuery(range(0, 0)))
        ArtifactContent.find_by_source(source).AndReturn(MockQuery(range(0,
                                                                         0)))
        db.delete(source)
        memcache.delete(IsA(str)).AndReturn(1)

        self.m.ReplayAll()
        ArtifactSourceAccessor.delete_by_name(name)
        self.m.VerifyAll()
Example #13
0
class APITest(unittest.TestCase):
    """
    The test for low level API calls
    """
    @classmethod
    def setUpClass(cls):
        magnetodb_api_fake.run_fake_magnetodb_api()

    @classmethod
    def tearDownClass(cls):
        magnetodb_api_fake.stop_fake_magnetodb_api()

    def setUp(self):
        self.storage_mocker = Mox()

    def tearDown(self):
        self.storage_mocker.UnsetStubs()

    def test_describe_unexisting_table(self):
        self.storage_mocker.StubOutWithMock(storage, 'describe_table')

        storage.describe_table(IgnoreArg(),
                               'test_table1').AndRaise(TableNotExistsException)

        self.storage_mocker.ReplayAll()

        headers = {
            'Host': 'localhost:8080',
            'Content-Type': 'application/x-amz-json-1.0',
            'X-Amz-Target': 'DynamoDB_20120810.DescribeTable'
        }

        conn = httplib.HTTPConnection('localhost:8080')
        conn.request("POST",
                     "/",
                     body='{"TableName": "test_table1"}',
                     headers=headers)

        response = conn.getresponse()

        json_response = response.read()
        response_model = json.loads(json_response)

        self.assertEqual(
            response_model['__type'],
            'com.amazonaws.dynamodb.v20111205#ResourceNotFoundException')

        self.assertEqual(
            response_model['message'],
            'The resource which is being requested does not exist.')

        self.assertEqual(400, response.status)

        self.assertEqual(response.getheader('Content-Type'),
                         'application/x-amz-json-1.0')
Example #14
0
def test_extract_zip_non_verbose():
    mox = Mox()
    class MyFs(io.FileSystem):
        stack = []
        abspath = mox.CreateMockAnything()
        pushd = mox.CreateMockAnything()
        popd = mox.CreateMockAnything()
        open_raw = mox.CreateMockAnything()
        mkdir = mox.CreateMockAnything()

    mox.StubOutWithMock(io, 'zipfile')

    filename = 'modafoca.zip'
    base_path = '../to/project'
    full_path = '/full/path/to/project'

    MyFs.abspath(base_path).AndReturn(full_path)
    MyFs.pushd(full_path)

    zip_mock = mox.CreateMockAnything()

    io.zipfile.ZipFile(filename).AndReturn(zip_mock)

    file_list = [
        'settings.yml',
        'app',
        'app/controllers.py'
    ]
    zip_mock.namelist().AndReturn(file_list)
    zip_mock.read('settings.yml').AndReturn('settings.yml content')
    zip_mock.read('app/controllers.py').AndReturn('controllers.py content')

    file_mock1 = mox.CreateMockAnything()
    MyFs.open_raw('settings.yml', 'w').AndReturn(file_mock1)
    file_mock1.write('settings.yml content')
    file_mock1.close()

    MyFs.open_raw('app', 'w').AndRaise(IOError('it is a directory, dumb ass!'))
    MyFs.mkdir('app')

    file_mock2 = mox.CreateMockAnything()
    MyFs.open_raw('app/controllers.py', 'w').AndReturn(file_mock2)
    file_mock2.write('controllers.py content')
    file_mock2.close()

    MyFs.popd()

    mox.ReplayAll()
    try:
        MyFs.extract_zip('modafoca.zip', base_path)
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #15
0
def test_after_each_all_is_executed_before_each_all():
    "terrain.before.each_all and terrain.after.each_all decorators"
    import lettuce
    from lettuce.fs import FeatureLoader
    world.all_steps = []

    mox = Mox()

    loader_mock = mox.CreateMock(FeatureLoader)
    mox.StubOutWithMock(lettuce.sys, 'path')
    mox.StubOutWithMock(lettuce, 'fs')
    mox.StubOutWithMock(lettuce.fs, 'FileSystem')
    mox.StubOutWithMock(lettuce, 'Feature')

    lettuce.fs.FeatureLoader('some_basepath').AndReturn(loader_mock)

    lettuce.sys.path.insert(0, 'some_basepath')
    lettuce.sys.path.remove('some_basepath')

    loader_mock.find_and_load_step_definitions()
    loader_mock.find_feature_files().AndReturn(['some_basepath/foo.feature'])
    lettuce.Feature.from_file('some_basepath/foo.feature'). \
        AndReturn(Feature.from_string(FEATURE2))

    mox.ReplayAll()

    runner = lettuce.Runner('some_basepath')
    CALLBACK_REGISTRY.clear()

    @before.all
    def set_state_to_before():
        world.all_steps.append('before')

    @step('append "during" to states')
    def append_during_to_all_steps(step):
        world.all_steps.append("during")

    @after.all
    def set_state_to_after(total):
        world.all_steps.append('after')
        isinstance(total, TotalResult)

    runner.run()

    mox.VerifyAll()

    assert_equals(
        world.all_steps,
        ['before', 'during', 'during', 'after'],
    )

    mox.UnsetStubs()
Example #16
0
def test_go():
    mox = Mox()
    mox.StubOutWithMock(bob, 'cherrypy')

    b = bob.Bob()
    b.configure = mox.CreateMockAnything()
    b.configure()
    bob.cherrypy.quickstart()
    mox.ReplayAll()
    try:
        b.go()
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #17
0
 def test_export_with_success(self):
     exporter = CSVExporter()
     product = Product(name='pname', title='ptitle', url='purl')
     writer, stream = self.get_writer()
     mock = Mox()
     mock.StubOutWithMock(__builtin__, 'open')
     filename = exporter.__get_filename__('Product')
     open(filename, 'w').AndReturn(stream)
     mock.ReplayAll()
     
     exporter.export('Product', [product])
     
     mock.VerifyAll()
     mock.UnsetStubs()
Example #18
0
def test_mkdir_success():
    mox = Mox()

    mox.StubOutWithMock(io, 'os')

    class MyFs(io.FileSystem):
        pass

    io.os.makedirs('/make/all/those/subdirs')

    mox.ReplayAll()
    try:
        MyFs.mkdir('/make/all/those/subdirs')
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
def test_can_be_init_memcache():
    mox = Mox()

    mox.StubOutWithMock(backend, 'memcache', use_mock_anything=True)

    servers = ["localhost:11211", "localhost:11212"]
    backend.memcache.Client(servers).AndReturn(True)

    mox.ReplayAll()
    try:
        cache = backend.MemcachedClass(server=servers, timeout=30)
        assert cache._cache
        assert cache.default_timeout == 30

        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #20
0
def test_get_content_from_path():
    from django.test.client import RequestFactory

    mox = Mox()
    _, model_base, manager, model, queryset = get_mocks(mox)
    settings = CustomSettings(WEB_ROOT="test_web_root")

    path_mock = 'some_path'

    request_mock = mox.CreateMockAnything()
    request_mock.META = mox.CreateMockAnything()
    request_mock.META.setdefault('SERVER_PORT', 80)
    request_mock.META.setdefault('SERVER_NAME', 'localhost')

    mox.StubOutWithMock(RequestFactory, 'get')
    RequestFactory.get.__call__(path_mock).AndReturn(request_mock)

    response_mock = mox.CreateMockAnything()
    response_mock.content = 'foo'
    response_mock.status_code = 200

    handler_mock = mox.CreateMockAnything()
    handler_mock.__call__().AndReturn(handler_mock)
    handler_mock.__call__(request_mock).AndReturn(response_mock)

    mox.ReplayAll()

    try:
        dummy_handler = staticgenerator.staticgenerator.DummyHandler
        staticgenerator.staticgenerator.DummyHandler = handler_mock

        instance = StaticGenerator(model_base=model_base,
                                   manager=manager,
                                   model=model,
                                   queryset=queryset,
                                   settings=settings)

        result = instance.get_content_from_path(path_mock)
    finally:
        staticgenerator.staticgenerator.DummyHandler = dummy_handler

    assert result == 'foo'
    mox.VerifyAll()
    mox.UnsetStubs()
def test_can_be_close():
    mox = Mox()

    mox.StubOutWithMock(backend, 'memcache', use_mock_anything=True)

    cache_mock = mox.CreateMockAnything()
    cache_mock.disconnect_all()

    backend.memcache.Client(["localhost:11211"]).AndReturn(cache_mock)

    mox.ReplayAll()
    try:
        memcache = backend.MemcachedClass(server=["localhost:11211"],
                                          timeout=30)
        memcache.close()

        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #22
0
def test_configure():
    mox = Mox()
    mock_parser = mox.CreateMockAnything()

    mox.StubOutWithMock(bob, 'yaml')
    config_validator = bob.ConfigValidator
    sponge_config = bob.SpongeConfig

    bob.ConfigValidator = mox.CreateMockAnything()
    bob.SpongeConfig = mox.CreateMockAnything()

    b = bob.Bob(parser=mock_parser)
    b.fs = mox.CreateMockAnything()

    b.fs.current_dir().AndReturn('should_be_current_dir')
    b.fs.current_dir('settings.yml'). \
         AndReturn('/current/path/settings-yaml')

    file_mock = mox.CreateMockAnything()
    b.fs.open('/current/path/settings-yaml', 'r'). \
         AndReturn(file_mock)

    file_mock.read().AndReturn('should-be-raw-yaml-text')
    bob.yaml.load('should-be-raw-yaml-text'). \
        AndReturn('should-be-config-dict')

    bob.ConfigValidator('should-be-config-dict'). \
        AndReturn('should-be-validator')

    config_mock = mox.CreateMockAnything()
    bob.SpongeConfig(cherrypy.config, 'should-be-validator'). \
        AndReturn(config_mock)

    config_mock.setup_all('should_be_current_dir')

    mox.ReplayAll()
    try:
        b.configure()
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
        bob.ConfigValidator = config_validator
        bob.SpongeConfig = sponge_config
Example #23
0
def tes_mkdir_raises_when_path_is_not_a_dir():
    mox = Mox()

    mox.StubOutWithMock(io, 'os')
    mox.StubOutWithMock(io.os, 'path')

    class MyFs(io.FileSystem):
        pass

    oserror = OSError()
    oserror.errno = 17

    io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror)
    io.os.isdir('/make/all/those/subdirs').AndReturn(False)
    mox.ReplayAll()
    try:
        assert_raises(OSError, MyFs.mkdir, '/make/all/those/subdirs')
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #24
0
def tes_mkdir_raises_on_oserror_errno_not_17():
    mox = Mox()

    mox.StubOutWithMock(io, 'os')
    mox.StubOutWithMock(io.os, 'path')

    class MyFs(io.FileSystem):
        pass

    oserror = OSError()
    oserror.errno = 0

    io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror)

    mox.ReplayAll()
    try:
        assert_raises(OSError, MyFs.mkdir, '/make/all/those/subdirs')
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
def test_can_be_get_key_from_expire():
    mox = Mox()

    class ShouldBeModule(object):
        def ShouldBeMethod(self, param=None):
            pass

        ShouldBeMethod.fn = ShouldBeMethod

    expire = "ShouldBeModule.ShouldBeMethod(should-be-params)"

    instance_mock = mox.CreateMockAnything()
    instance_mock.id = 101
    instance_mock.ShouldBeMethod = "should-be-method-instance"

    cached_extension = cache.CachedExtension()

    mox.StubOutWithMock(cached_extension,
                        'prepare_parameters',
                        use_mock_anything=True)
    mox.StubOutWithMock(cached_extension, 'load_model', use_mock_anything=True)

    cached_extension.prepare_parameters(
        instance_mock,
        "should-be-params").AndReturn({"param": "should-be-prepare-params"})

    module_instance = ShouldBeModule()
    cached_extension.load_model('shouldbemodule',
                                'ShouldBeModule').AndReturn(module_instance)

    mox.ReplayAll()
    try:

        md5, key = cached_extension.get_key_from_expires(instance_mock, expire)
        assert md5 == hashlib.md5(
            "mss.tests.unit.core.cache.test_cache.ShouldBeModule().ShouldBeMethod(param=should-be-prepare-params)"
        ).hexdigest()

        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #26
0
def test_mkdir_ignore_dirs_already_exists():
    mox = Mox()

    mox.StubOutWithMock(io, 'os')
    mox.StubOutWithMock(io.os, 'path')

    class MyFs(io.FileSystem):
        pass

    oserror = OSError()
    oserror.errno = 17

    io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror)
    io.os.path.isdir('/make/all/those/subdirs').AndReturn(True)

    mox.ReplayAll()
    try:
        MyFs.mkdir('/make/all/those/subdirs')
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
Example #27
0
    def test_caching_return_if_already_exists(self):
        mox = Mox()

        old_jpeg = controllers.jpeg
        old_picture = controllers.picture
        old_static = controllers.static

        mox.StubOutWithMock(controllers, 'static')
        controllers.jpeg = mox.CreateMockAnything()
        controllers.picture = mox.CreateMockAnything()

        cache_at = '/full/path/to/cache'

        class ImageHandlerStub(controllers.ImageHandler):
            fs = mox.CreateMockAnything()

        ImageHandlerStub.fs.exists(cache_at).AndReturn(True)

        controllers.jpeg(path='imgs/image.jpg')
        ImageHandlerStub.fs.join(cache_at, 'imgs/image.jpg'). \
                         AndReturn('/should/be/cache/full/path.jpg')

        ImageHandlerStub.fs.exists('/should/be/cache/full/path.jpg'). \
                         AndReturn(True)
        controllers.static.serve_file('/should/be/cache/full/path.jpg',
                              'image/jpeg'). \
                   AndReturn('should-be-image-data')

        mox.ReplayAll()
        try:
            img = ImageHandlerStub(cache_at)
            assert img.should_cache
            assert_equal(img.cache_path, cache_at)
            got = img('imgs', 'image.jpg')
            assert_equal(got, 'should-be-image-data')
            mox.VerifyAll()
        finally:
            controllers.jpeg = old_jpeg
            controllers.picture = old_picture
            mox.UnsetStubs()
def test_can_get_many():
    mox = Mox()

    keys = ["should-be-key", "should-be-key-1", "should-be-key-2"]
    values = ["should-be-value", "should-be-value", "should-be-value"]

    mox.StubOutWithMock(backend, 'memcache', use_mock_anything=True)

    cache_mock = mox.CreateMockAnything()
    cache_mock.get_multi(keys).AndReturn(values)

    backend.memcache.Client(["localhost:11211"]).AndReturn(cache_mock)

    mox.ReplayAll()
    try:
        memcache = backend.MemcachedClass(server=["localhost:11211"],
                                          timeout=30)
        assert memcache.get_many(keys) == values

        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
def test_can_be_get_default():
    mox = Mox()

    key = "should-be-key"

    mox.StubOutWithMock(backend, 'memcache', use_mock_anything=True)

    cache_mock = mox.CreateMockAnything()
    cache_mock.get(key).AndReturn(None)

    backend.memcache.Client(["localhost:11211"]).AndReturn(cache_mock)

    mox.ReplayAll()
    try:
        memcache = backend.MemcachedClass(server=["localhost:11211"],
                                          timeout=30)
        assert memcache.get(
            key,
            default="should-be-value-default") == "should-be-value-default"

    finally:
        mox.UnsetStubs()
Example #30
0
def test_locate_non_recursive():
    mox = Mox()

    old_glob = io.glob
    io.glob = mox.CreateMockAnything()

    base_path = '../to/project'
    full_path = '/full/path/to/project'

    class MyFs(io.FileSystem):
        stack = []
        abspath = mox.CreateMockAnything()

    io.glob('%s/*match*.py' % full_path)
    MyFs.abspath(base_path).AndReturn(full_path)
    mox.ReplayAll()
    try:
        MyFs.locate(base_path, '*match*.py', recursive=False)
        mox.VerifyAll()
    finally:
        mox.UnsetStubs()
        io.glob = old_glob