Ejemplo n.º 1
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()
Ejemplo n.º 2
0
class SeeAlsoFinderTest(unittest.TestCase):
    def setUp(self):
        self.finder = SeeAlsoFinder()
        self.mox = Mox()
        debian.services.RES_BASEURI = "base"
        debian.services.FROM_GRAPH = None

    def test__fetch_seealso_uris(self):
        sourcename = "pkg"
        unversionedsourceuri = "base/source/%s" % sourcename
        mock = self.mox.CreateMock(SPARQLQueryProcessor)
        expectedarg = \
            r".+SELECT\s*\?uri.+\<%s\>\sa\sdeb:UnversionedSource\s*;\s*rdfs:seeAlso\s\?uri" % \
            re.escape(unversionedsourceuri)
        mock.execute_query(Regex(expectedarg, flags=re.DOTALL))
        binding1 = {'uri': {'value': "http://example.org/1"}}
        binding2 = {'uri': {'value': "http://example.org/2"}}
        bindings = [binding1, binding2]
        fakeresults = {'results': {'bindings': bindings}}
        self.finder.processor = mock
        self.mox.ReplayAll()
        self.finder.processor.results = fakeresults
        uris = self.finder._fetch_seealso_uris(unversionedsourceuri)
        self.mox.VerifyAll()
        self.assertEqual(2, len(uris))
        self.assertTrue("http://example.org/1" in uris)
        self.assertTrue("http://example.org/2" in uris)

    def test_find_forbidden_characters(self):
        self.assertRaises(SPARQLQueryBuilderPackageNameSchemeError,
                          self.finder.find, "{}@")

    def test_find(self):
        srcpkgname = "source"
        srcpkguri = "base/source/%s" % srcpkgname
        self.mox.StubOutWithMock(self.finder, "_fetch_seealso_uris")
        returnvals = ["http://example.org/1", "http://example.org/2"]
        self.finder._fetch_seealso_uris(srcpkguri).AndReturn(returnvals)
        self.mox.ReplayAll()
        uris = self.finder.find(srcpkgname)
        self.mox.VerifyAll()
        self.assertEqual(2, len(uris))
        self.assertTrue("http://example.org/1" in uris)
        self.assertTrue("http://example.org/2" in uris)

    def test_find_escape(self):
        srcpkgname = "source.+-"
        srcpkguri = "base/source/%s" % "source.%2B-"
        self.mox.StubOutWithMock(self.finder, "_fetch_seealso_uris")
        returnvals = ["http://example.org/1", "http://example.org/2"]
        self.finder._fetch_seealso_uris(srcpkguri).AndReturn(returnvals)
        self.mox.ReplayAll()
        uris = self.finder.find(srcpkgname)
        self.mox.VerifyAll()
Ejemplo n.º 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()
Ejemplo n.º 4
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()
Ejemplo n.º 5
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__
def test_delete_raises_when_unable_to_delete_file():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    fs_mock = mox.CreateMockAnything()

    fs_mock.join("test_web_root",
                 "some_path").AndReturn("test_web_root/some_path")
    fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root")
    fs_mock.exists("test_web_root/some_path").AndReturn(True)
    fs_mock.remove("test_web_root/some_path").AndRaise(ValueError())

    settings = CustomSettings(WEB_ROOT="test_web_root")

    mox.ReplayAll()

    instance = StaticGenerator(http_request=http_request,
                               model_base=model_base,
                               manager=manager,
                               model=model,
                               queryset=queryset,
                               settings=settings,
                               fs=fs_mock)

    try:
        instance.delete_from_path("some_path")
    except StaticGeneratorException, e:
        assert str(e) == 'Could not delete file: test_web_root/some_path'
        mox.VerifyAll()
        return
def test_publish_raises_when_unable_to_create_folder():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    fs_mock = mox.CreateMockAnything()
    fs_mock.join("test_web_root",
                 "some_path").AndReturn("test_web_root/some_path")
    fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root")
    fs_mock.exists("test_web_root").AndReturn(False)

    fs_mock.makedirs("test_web_root").AndRaise(ValueError())

    settings = CustomSettings(WEB_ROOT="test_web_root")

    mox.ReplayAll()

    instance = StaticGenerator(http_request=http_request,
                               model_base=model_base,
                               manager=manager,
                               model=model,
                               queryset=queryset,
                               settings=settings,
                               fs=fs_mock)

    try:
        instance.publish_from_path("some_path", content="some_content")
    except StaticGeneratorException, e:
        assert str(e) == 'Could not create the directory: test_web_root'
        mox.VerifyAll()
        return
def test_extract_resources_when_resource_is_a_model():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    class Model(object):
        def get_absolute_url(self):
            return 'some_model_url'

    resources_mock = Model()
    model = Model

    settings = CustomSettings(WEB_ROOT="some_web_root")

    mox.ReplayAll()

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

    assert len(instance.resources) == 1
    assert instance.resources[0] == 'some_model_url'
    mox.VerifyAll()
Ejemplo n.º 9
0
def test_publish_raises_when_unable_to_create_temp_file():
    mox = Mox()
    _, model_base, manager, model, queryset = get_mocks(mox)

    FAKE_WEB_ROOT = 'test_web_root'

    mox.StubOutWithMock(tempfile, 'mkstemp')
    tempfile.mkstemp(dir="test_web_root").AndRaise(ValueError())

    settings = CustomSettings(WEB_ROOT=FAKE_WEB_ROOT)

    mox.ReplayAll()

    with remove_web_root_from_settings():
        instance = StaticGenerator(
            model_base=model_base,
            manager=manager,
            model=model,
            queryset=queryset,
            settings=settings,
        )

        try:
            instance.publish_from_path("some_path", content="some_content")
        except StaticGeneratorException, e:
            assert str(
                e) == 'Could not create the file: test_web_root/some_path'
            mox.VerifyAll()
            return
        finally:
Ejemplo n.º 10
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()
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    def test_get_registers_appropriate_tasks(self):
        moxer = Mox()
        request, response = new_mock_request_response(moxer)

        _stub_taskqueue(moxer)
        moxer.StubOutWithMock(Feed, "find_active", use_mock_anything=True)

        def create_call(i):
            source_name = "source-%i" % i
            source = MockEntity(key_name=source_name, name=source_name)
            return MockEntity(key_name="feed-%i" % i,
                              artifact_source=source,
                              url="hi")

        q_range = xrange(0, 5)
        Feed.find_active().AndReturn(
            MockQuery(q_range, create_call=create_call))

        # expects queued tasks for each feed
        for i in q_range:
            taskqueue.add(name=IgnoreArg(), url=IgnoreArg())

        moxer.ReplayAll()
        handler = CronIngestDriverHandler()
        handler.initialize(request, response)
        handler.get()
        moxer.VerifyAll()
Ejemplo n.º 13
0
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()
Ejemplo n.º 14
0
def test_jpeg_success():
    mox = Mox()

    path = '/path/to/mocked/img.jpg'

    mox.StubOutWithMock(image, 'Image')
    mox.StubOutWithMock(image, 'StringIO')

    stringio_mock = mox.CreateMockAnything()
    return_mock = mox.CreateMockAnything()
    img_mock = mox.CreateMockAnything()

    stringio_mock.getvalue().AndReturn(return_mock)

    image.StringIO.StringIO().AndReturn(stringio_mock)
    image.Image.open(path).AndReturn(img_mock)

    img_mock.save(stringio_mock, "JPEG", quality=100)

    cherrypy.config['image.dir'] = path

    mox.ReplayAll()

    return_got = image.jpeg(path)
    assert return_got == return_mock, 'The return of image.jpeg() should be %r, got %r' % (
        return_mock, return_got)
    mime = cherrypy.response.headers['Content-type']
    assert mime == 'image/jpeg', 'The response header "Content-type" should be image/jpeg, but got %r' % mime

    mox.VerifyAll()

    del cherrypy.config['image.dir']
Ejemplo n.º 15
0
def test_picture_with_center_true_will_create_new_image_and_paste():
    base_path = '/base/path'
    path = 'image.jpg'

    mox = Mox()

    mox.StubOutWithMock(image, 'Image')
    mox.StubOutWithMock(image, 'StringIO')

    img_mock = mox.CreateMockAnything()
    img_mock.size = 300, 300

    stringio_mock = mox.CreateMockAnything()
    return_mock = mox.CreateMockAnything()

    stringio_mock.getvalue().AndReturn(return_mock)
    image.StringIO.StringIO().AndReturn(stringio_mock)

    cherrypy.config['image.dir'] = base_path

    new_img_mock = mox.CreateMockAnything()

    new_img_mock.paste(img_mock, (-100, -100))
    new_img_mock.save(stringio_mock, 'JPEG', quality=100)

    image.Image.open(join(base_path, path)).AndReturn(img_mock)
    image.Image.new('RGBA', (100, 100), 0xffffff).AndReturn(new_img_mock)

    mox.ReplayAll()
    ret = image.picture(path, 100, 100, crop=False, center=True)

    assert ret == return_mock, "Expected %r. Got %r." % (return_mock, ret)
    mox.VerifyAll()

    del cherrypy.config['image.dir']
Ejemplo n.º 16
0
def test_publish_raises_when_unable_to_create_folder():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)
    FAKE_WEB_ROOT = 'test_web_root'

    mox.StubOutWithMock(os, 'makedirs')
    mox.StubOutWithMock(os.path, 'exists')
    os.makedirs(FAKE_WEB_ROOT).AndRaise(ValueError())
    os.path.exists(FAKE_WEB_ROOT).AndReturn(False)

    settings = CustomSettings(WEB_ROOT=FAKE_WEB_ROOT)

    mox.ReplayAll()

    with remove_web_root_from_settings():
        instance = StaticGenerator(
            http_request=http_request,
            model_base=model_base,
            manager=manager,
            model=model,
            queryset=queryset,
            settings=settings,
        )

        try:
            instance.publish_from_path("some_path", content="some_content")
        except StaticGeneratorException, e:
            assert str(e) == 'Could not create the directory: ' + FAKE_WEB_ROOT
            mox.VerifyAll()
            return
        finally:
Ejemplo n.º 17
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()
Ejemplo n.º 18
0
def test_delete_raises_when_unable_to_delete_file():
    mox = Mox()

    FAKE_WEB_ROOT = 'test_web_root'
    FILE_PATH = 'some_path'
    FILE_RELATIVE_PATH = os.path.join(FAKE_WEB_ROOT, FILE_PATH)

    settings = CustomSettings(WEB_ROOT=FAKE_WEB_ROOT)

    mox.StubOutWithMock(os.path, 'exists')
    mox.StubOutWithMock(os, 'remove')

    os.path.exists(FILE_RELATIVE_PATH).AndReturn(True)
    os.remove(FILE_RELATIVE_PATH).AndRaise(Exception())

    mox.ReplayAll()

    with remove_web_root_from_settings():
        instance = StaticGenerator(settings=settings, )

        try:
            instance.delete_from_path(FILE_PATH)
        except StaticGeneratorException, e:
            assert str(e) == 'Could not delete file: {file_path}'.format(
                file_path=FILE_RELATIVE_PATH)
            mox.VerifyAll()
            return
        finally:
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()
def test_get_filename_from_path_when_path_ends_with_slash():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)
    settings = CustomSettings(WEB_ROOT="test_web_root")

    fs_mock = mox.CreateMockAnything()
    fs_mock.join(
        "test_web_root",
        "foo/bar/index.html").AndReturn("test_web_root/foo/bar/index.html")
    fs_mock.dirname("test_web_root/foo/bar/index.html").AndReturn(
        "test_web_root/foo/bar")

    path_mock = '/foo/bar/'

    mox.ReplayAll()

    instance = StaticGenerator(http_request=http_request,
                               model_base=model_base,
                               manager=manager,
                               model=model,
                               queryset=queryset,
                               settings=settings,
                               fs=fs_mock)

    result = instance.get_filename_from_path(path_mock)

    assert result == ('test_web_root/foo/bar/index.html',
                      'test_web_root/foo/bar')
    mox.VerifyAll()
Ejemplo n.º 21
0
    def test_act_direct_message(self):
        moxer = Mox()

        api = _create_default_mocks(moxer)
        _build_standard_config(moxer)
        bundle = _create_actor_and_delegates(api, moxer)
        actor = bundle.actor

        direct_id = 1
        direct = moxer.CreateMock(twitter.DirectMessage)
        user = moxer.CreateMock(twitter.User)
        direct.id = direct_id
        direct.sender_screen_name = "mikemattozzi"
        direct.text = "why is blood spattered all over your car?"

        _return_direct_messages(api, [direct])

        post = moxer.CreateMockAnything()
        post.id = 101

        _return_replies(api, ())
        TwitterResponseAccessor.get_by_message_id(str(direct_id))
        ArtifactAccessor.search("spattered").AndReturn(create_content_list(10))

        # response
        api.PostDirectMessage(direct.sender_screen_name,
                              IgnoreArg()).AndReturn(post)
        TwitterResponseAccessor.create(str(direct.id),
                                       response_id=str(post.id),
                                       user=direct.sender_screen_name)
        post.AsDict().AndReturn({})

        moxer.ReplayAll()
        actor.act()
        moxer.VerifyAll()
def test_publish_from_path():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    fs_mock = mox.CreateMockAnything()
    fs_mock.join("test_web_root",
                 "some_path").AndReturn("test_web_root/some_path")
    fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root")
    fs_mock.exists("test_web_root").AndReturn(True)

    f = mox.CreateMockAnything()
    filename = "some_temp_file"
    fs_mock.tempfile(directory="test_web_root").AndReturn([f, filename])
    fs_mock.write(f, "some_content")
    fs_mock.close(f)
    fs_mock.chmod(
        filename, stat.S_IREAD | stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR
        | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    fs_mock.rename('some_temp_file', 'test_web_root/some_path')

    settings = CustomSettings(WEB_ROOT="test_web_root")

    mox.ReplayAll()

    instance = StaticGenerator(http_request=http_request,
                               model_base=model_base,
                               manager=manager,
                               model=model,
                               queryset=queryset,
                               settings=settings,
                               fs=fs_mock)

    instance.publish_from_path("some_path", content="some_content")

    mox.VerifyAll()
Ejemplo n.º 23
0
    def test_act_public_message(self):
        moxer = Mox()

        bundle = _create_api_actor_and_selector(moxer)
        api = bundle.api
        actor = bundle.actor
        analyzer = bundle.analyzer

        _no_direct_messages(api)

        msg = _create_message(
            moxer, 1, "mmattozzi",
            "@livelock why is blood spattered all over @mhawthorne's car?")

        _mentions(api, msg)

        _should_respond(analyzer, msg, True)
        _no_response_found(msg)
        _search_results("spattered", create_content_list(1))
        response = _post_response_to(moxer, api, msg)
        _save_response(msg, response)
        _format(response)

        moxer.ReplayAll()
        actor.act()
        moxer.VerifyAll()
def test_delete_from_path():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    fs_mock = mox.CreateMockAnything()
    fs_mock.join("test_web_root",
                 "some_path").AndReturn("test_web_root/some_path")
    fs_mock.dirname("test_web_root/some_path").AndReturn("test_web_root")
    fs_mock.exists("test_web_root/some_path").AndReturn(True)
    fs_mock.remove("test_web_root/some_path")

    fs_mock.rmdir("test_web_root")

    settings = CustomSettings(WEB_ROOT="test_web_root")

    mox.ReplayAll()

    instance = StaticGenerator(http_request=http_request,
                               model_base=model_base,
                               manager=manager,
                               model=model,
                               queryset=queryset,
                               settings=settings,
                               fs=fs_mock)

    instance.delete_from_path("some_path")

    mox.VerifyAll()
Ejemplo n.º 25
0
class MoxTestBase(object):
    def setup_method(self, method):
        self.mox = Mox()

    def teardown_method(self, method):
        self.mox.UnsetStubs()
        self.mox.VerifyAll()
Ejemplo n.º 26
0
 def _test_post_no_user(self):
     moxer = Mox()
     
     request, response = new_mock_request_response(moxer)
     moxer.StubOutWithMock(users, "get_current_user", use_mock_anything=True)
     moxer.StubOutWithMock(User, "__init__", use_mock_anything=True)
     moxer.StubOutWithMock(Feed, "get_by_source_name", use_mock_anything=True)
     moxer.StubOutWithMock(model, "ingest_feed_entries")
     
     source_name = "hi"
     username = Services.API_USER
     user = MockEntity(key_name=username, email=lambda: username)
     
     # passes auth (via cron)
     users.get_current_user().AndReturn(user)
     handler = IngestHandler()
     # no logged in user
     users.get_current_user()
     User.__init__(username)
     handler.initialize(request, response)
     feed = MockEntity(key_name=source_name, url="no")
     Feed.get_by_source_name(source_name, return_none=True).AndReturn(feed)
     model.ingest_feed_entries(feed, None, error_call=IgnoreArg()).AndReturn(())
     
     moxer.ReplayAll()
     handler.post(source_name)
     moxer.VerifyAll()
Ejemplo n.º 27
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()
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
def test_picture_with_crop_true_will_crop_to_fit():
    base_path = '/basepath/for/test_picture_success'
    path = 'my_picture.jpg'

    mox = Mox()

    mox.StubOutWithMock(image, 'Image')
    mox.StubOutWithMock(image, 'StringIO')
    mox.StubOutWithMock(image, 'crop_to_fit')

    img_mock = mox.CreateMockAnything()
    img_mock.size = 300, 300

    stringio_mock = mox.CreateMockAnything()
    return_mock = mox.CreateMockAnything()

    stringio_mock.getvalue().AndReturn(return_mock)

    image.StringIO.StringIO().AndReturn(stringio_mock)

    cherrypy.config['image.dir'] = base_path

    image.Image.open(join(base_path, path)).AndReturn(img_mock)
    img_mock.save(stringio_mock, 'JPEG', quality=100)
    image.crop_to_fit(img_mock, (100, 100)).AndReturn(img_mock)

    mox.ReplayAll()

    ret = image.picture(path, 100, 100, crop=True, center=False)
    assert ret == return_mock, "Expected %r. Got %r." % (return_mock, ret)

    mox.VerifyAll()
    del cherrypy.config['image.dir']
Ejemplo n.º 30
0
def test_publish_loops_through_all_resources():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    fs_mock = mox.CreateMockAnything()
    f = mox.CreateMockAnything()
    fs_mock.join(
        'test_web_root',
        'some_path_1/index.html').AndReturn('test_web_root/some_path_1')
    fs_mock.dirname('test_web_root/some_path_1').AndReturn('test_web_root')
    fs_mock.exists("test_web_root").AndReturn(True)
    filename = "some_temp_file"
    fs_mock.tempfile(directory="test_web_root").AndReturn([f, filename])
    fs_mock.write(f, "some_content")
    fs_mock.close(f)
    fs_mock.chmod(
        filename, stat.S_IREAD | stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR
        | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    fs_mock.rename('some_temp_file', 'test_web_root/some_path_1')

    fs_mock.join(
        'test_web_root',
        'some_path_2/index.html').AndReturn('test_web_root/some_path_2')
    fs_mock.dirname('test_web_root/some_path_2').AndReturn('test_web_root')
    fs_mock.exists("test_web_root").AndReturn(True)
    filename = "some_temp_file"
    fs_mock.tempfile(directory="test_web_root").AndReturn([f, filename])
    fs_mock.write(f, "some_content")
    fs_mock.close(f)
    fs_mock.chmod(
        filename, stat.S_IREAD | stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR
        | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    fs_mock.rename('some_temp_file', 'test_web_root/some_path_2')

    settings = CustomSettings(WEB_ROOT="test_web_root")

    mox.ReplayAll()

    try:
        get_content_from_path = StaticGenerator.get_content_from_path
        StaticGenerator.get_content_from_path = lambda self, path: "some_content"
        instance = StaticGenerator("some_path_1",
                                   "some_path_2",
                                   http_request=http_request,
                                   model_base=model_base,
                                   manager=manager,
                                   model=model,
                                   queryset=queryset,
                                   settings=settings,
                                   fs=fs_mock)

        instance.publish()

        mox.VerifyAll()
    finally:
        StaticGenerator.get_content_from_path = get_content_from_path