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']
Exemple #2
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
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()
Exemple #4
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_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']
Exemple #6
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()
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']
Exemple #8
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
Exemple #9
0
def test_config_validator_validate_calls_validation_methods():
    mocker = Mox()
    cp = ConfigValidator({})
    cp.validate_mandatory = mocker.CreateMockAnything()
    cp.validate_optional = mocker.CreateMockAnything()

    cp.validate_mandatory()

    mocker.ReplayAll()
    cp.validate()
    mocker.VerifyAll()
Exemple #10
0
def test_run_calls_go():
    mox = Mox()

    mock_parser = mox.CreateMockAnything()
    mock_parser.parse_args().AndReturn(("options", ['go']))
    b = bob.Bob(parser=mock_parser)
    b.go = mox.CreateMockAnything()
    b.go()

    mox.ReplayAll()
    b.run()
    mox.VerifyAll()
Exemple #11
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()
Exemple #12
0
def test_run_calls_create_with_second_argument():
    mox = Mox()

    mock_parser = mox.CreateMockAnything()
    mock_parser.parse_args().AndReturn(("options", ['create', 'some']))
    b = bob.Bob(parser=mock_parser)
    b.create = mox.CreateMockAnything()
    b.create('some')

    mox.ReplayAll()
    b.run()
    mox.VerifyAll()
Exemple #13
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_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()
Exemple #15
0
def test_start():
    mox = Mox()
    b = bob.Bob()
    b.fs = mox.CreateMockAnything()
    b.create = mox.CreateMockAnything()
    b.go = mox.CreateMockAnything()

    b.create('foo-bar')
    b.fs.pushd('foo-bar')
    b.go()

    mox.ReplayAll()

    b.start('foo-bar')

    mox.VerifyAll()
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()
def test_delete_ignores_folder_delete_when_unable_to_delete_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/some_path").AndReturn(True)
    fs_mock.remove("test_web_root/some_path")

    fs_mock.rmdir("test_web_root").AndRaise(OSError())

    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")

    assert True, "Should work even when raising OSError"
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()
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_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
Exemple #21
0
    def test_caching_opens_if_does_not_exist(self):
        mox = Mox()

        old_jpeg = controllers.jpeg
        old_picture = controllers.picture
        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').AndReturn('fake-img')
        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(False)

        ImageHandlerStub.fs.dirname('/should/be/cache/full/path.jpg'). \
                         AndReturn('dir-name')

        ImageHandlerStub.fs.mkdir('dir-name')

        file_mock = mox.CreateMockAnything()
        ImageHandlerStub.fs.open_raw('/should/be/cache/full/path.jpg', 'w'). \
                         AndReturn(file_mock)

        file_mock.write('fake-img')
        file_mock.close()

        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, 'fake-img')
            mox.VerifyAll()
        finally:
            controllers.jpeg = old_jpeg
            controllers.picture = old_picture
Exemple #22
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()
Exemple #23
0
def test_create_success():
    mox = Mox()
    b = bob.Bob()
    b.fs = mox.CreateMockAnything()
    b.fs.join = join

    mox.StubOutWithMock(bob, 'SpongeData')
    mox.StubOutWithMock(bob, 'yaml')

    full_path = '/full/path/to/my-project'
    b.fs.current_dir('my-project'). \
         AndReturn(full_path)

    b.fs.exists(full_path). \
         AndReturn(False)

    b.fs.mkdir(full_path)

    file_mock = mox.CreateMockAnything()
    b.fs.open(join(full_path, 'settings.yml'), 'w'). \
         AndReturn(file_mock)

    expected_dict = basic_config.copy()
    expected_dict['application'].update({
        'static': {
            '/media': join('media')
        },
        'path': join('app', 'controllers.py'),
        'image-dir': join('media', 'img'),
        'template-dir': join('templates'),
    })

    bob.yaml.dump(expected_dict, indent=True).AndReturn('should-be-a-yaml')
    file_mock.write('should-be-a-yaml')
    file_mock.close()

    bob.SpongeData.get_file('project.zip'). \
        AndReturn('should-be-path-to-zip-file')

    b.fs.extract_zip('should-be-path-to-zip-file', full_path)

    mox.ReplayAll()
    b.create('my-project')
    mox.VerifyAll()
def test_not_found_raises_proper_exception():
    mox = Mox()

    http_request, 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')

    http_request.__call__().AndReturn(request_mock)

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

    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(http_request=http_request,
                                   model_base=model_base,
                                   manager=manager,
                                   model=model,
                                   queryset=queryset,
                                   settings=settings)

        result = instance.get_content_from_path(path_mock)
    except StaticGeneratorException, e:
        assert str(
            e
        ) == 'The requested page("some_path") returned http code 404. Static Generation failed.'
        mox.VerifyAll()
        return
def test_extract_resources_when_resource_is_a_model_base():
    mox = Mox()
    http_request, model_base, manager, model, queryset = get_mocks(mox)

    class ModelBase(object):
        def __init__(self, manager):
            self._default_manager = manager

    instance_mock = mox.CreateMockAnything()
    instance_mock.get_absolute_url().AndReturn('some_url1')

    instance_mock2 = mox.CreateMockAnything()
    instance_mock2.get_absolute_url().AndReturn('some_url2')

    instance_mocks = [instance_mock, instance_mock2]

    mock_manager = mox.CreateMockAnything()
    mock_manager.all().AndReturn(instance_mocks)

    resources_mock = ModelBase(mock_manager)
    model_base = ModelBase

    model.__instancecheck__(resources_mock).AndReturn(False)
    manager.__instancecheck__(mock_manager).AndReturn(True)
    queryset.__instancecheck__(instance_mocks).AndReturn(True)

    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) == 2
    assert instance.resources[0] == 'some_url1'
    assert instance.resources[1] == 'some_url2'
    mox.VerifyAll()
Exemple #26
0
def test_request_exception_raises_proper_exception():
    from django.test.client import RequestFactory

    mox = Mox()

    http_request, 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)

    handler_mock = mox.CreateMockAnything()
    handler_mock.__call__().AndReturn(handler_mock)
    handler_mock.__call__(request_mock).AndRaise(ValueError("exception"))

    mox.ReplayAll()

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

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

        instance.get_content_from_path(path_mock)
    except StaticGeneratorException, e:
        assert str(
            e
        ) == 'The requested page("some_path") raised an exception. Static Generation failed. Error: exception'
        mox.VerifyAll()
        return
Exemple #27
0
def test_bad_request_raises_proper_exception():
    from django.test.client import RequestFactory

    mox = Mox()

    mox.StubOutWithMock(RequestFactory, 'get')

    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')

    RequestFactory.get.__call__(path_mock).AndReturn(request_mock)

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

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

    mox.ReplayAll()

    try:
        with remove_web_root_from_settings():
            dummy_handler = staticgenerator.staticgenerator.DummyHandler
            staticgenerator.staticgenerator.DummyHandler = handler_mock

            instance = StaticGenerator(settings=settings)

            instance.get_content_from_path(path_mock)
    except StaticGeneratorException, e:
        assert str(
            e
        ) == 'The requested page("some_path") returned http code 500. Static Generation failed.'
        mox.VerifyAll()
        return
Exemple #28
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()
Exemple #29
0
def test_exists():
    mox = Mox()
    old_exists = io.exists
    io.exists = mox.CreateMockAnything()

    io.exists('some path').AndReturn('should be bool')

    mox.ReplayAll()
    try:
        got = io.FileSystem.exists('some path')
        assert_equals(got, 'should be bool')
        mox.VerifyAll()
    finally:
        io.exists = old_exists
Exemple #30
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()