Example #1
1
def test_gravatar_url():
    """Test that the gravatar url is generated correctly"""
    app = Flask(__name__)

    with app.test_request_context("/"):
        app.debug = True
        url = gravatar_url("test@test.com")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        url = gravatar_url("test@test.com", 200)
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?s=200&d=mm")

        app.debug = False

        url = gravatar_url("test@test.com")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        app.config["SITE_URL"] = "http://www.site.com"

        url = gravatar_url("test@test.com")
        eq_(
            url,
            "http://www.gravatar.com/avatar/"
            "b642b4217b34b1e8d3bd915fc65c4452"
            "?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2Fdefault-avatar.png",
        )
def test_resource2():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    @api.resource(name="hi")
    class Hello(Resource):
        def get(self, *args, **kvargs):
            # import pdb
            # pdb.set_trace()
            return "hello"

        def post_login(self, *args, **kvargs):
            return "login"

    # import pdb
    # pdb.set_trace()
    # api.add_resource(Hello)
    client = app.test_client()
    with app.test_request_context("/hi"):
        # import pdb
        # pdb.set_trace()
        assert url_for("hi") == "/hi"
        assert url_for("hi@login") == "/hi/login"

    with app.test_request_context("/hi/login"):
        assert request.endpoint == "hi@login"
        assert True

    assert "hello" == client.get("/hi").data
    assert "login" == client.post("/hi/login").data
Example #3
0
def test_context_local():
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    ghbp1 = make_github_blueprint("foo1", "bar1", redirect_to="url1")
    app1.register_blueprint(ghbp1)
    ghbp1.token_getter(lambda: {"access_token": "app1"})

    app2 = Flask(__name__)
    ghbp2 = make_github_blueprint("foo2", "bar2", redirect_to="url2")
    app2.register_blueprint(ghbp2)
    ghbp2.token_getter(lambda: {"access_token": "app2"})

    # outside of a request context, referencing functions on the `github` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        github.get("https://google.com")

    # inside of a request context, `github` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        github.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"


    with app2.test_request_context("/"):
        app2.preprocess_request()
        github.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Example #4
0
class LoginInSessionTestCase(unittest.TestCase):
    ''' Tests for login_user_in_session function '''

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'deterministic'
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)

        unittest.TestCase.setUp(self)

    def test_login_user_in_session(self):
        with self.app.test_request_context():
            session = {}
            login_user_in_session(session, notch)
            self.assertTrue('user_id' in session)
            self.assertTrue('_fresh' in session)
            self.assertTrue('_id' in session)
            self.assertTrue('remember' not in session)

    def test_login_user_in_session_remember(self):
        with self.app.test_request_context():
            session = {}
            login_user_in_session(session, notch, remember=True)
            self.assertTrue('user_id' in session)
            self.assertTrue('_fresh' in session)
            self.assertTrue('_id' in session)
            self.assertTrue(session['remember'])
    def test_heartbeat(self):
        app = Flask(__name__)
        controller = HeartbeatController()

        with app.test_request_context('/'):
            response = controller.heartbeat()
        eq_(200, response.status_code)
        eq_(controller.HEALTH_CHECK_TYPE, response.headers.get('Content-Type'))
        data = json.loads(response.data)
        eq_('pass', data['status'])

        # Create a .version file.
        root_dir = os.path.join(os.path.split(__file__)[0], "..", "..")
        version_filename = os.path.join(root_dir, controller.VERSION_FILENAME)
        with open(version_filename, 'w') as f:
            f.write('ba.na.na-10-ssssssssss')

        # Create a mock configuration object to test with.
        class MockConfiguration(Configuration):
            instance = dict()

        with app.test_request_context('/'):
            response = controller.heartbeat(conf_class=MockConfiguration)
        if os.path.exists(version_filename):
            os.remove(version_filename)

        eq_(200, response.status_code)
        content_type = response.headers.get('Content-Type')
        eq_(controller.HEALTH_CHECK_TYPE, content_type)

        data = json.loads(response.data)
        eq_('pass', data['status'])
        eq_('ba.na.na', data['version'])
        eq_('ba.na.na-10-ssssssssss', data['releaseID'])
Example #6
0
class SearchTestBase(unittest.TestCase):
    def setUp(self):
        class TestConfig(object):
            SQLALCHEMY_TRACK_MODIFICATIONS = True
            SQLALCHEMY_DATABASE_URI = 'sqlite://'
            DEBUG = True
            TESTING = True
            MSEARCH_INDEX_NAME = mkdtemp()
            # MSEARCH_BACKEND = 'whoosh'

        self.app = Flask(__name__)
        self.app.config.from_object(TestConfig())
        # we need this instance to be:
        #  a) global for all objects we share and
        #  b) fresh for every test run
        global db
        db = SQLAlchemy(self.app)
        self.search = Search(self.app, db=db)
        self.Post = None

    def init_data(self):
        if self.Post is None:
            self.fail('Post class not defined')
        with self.app.test_request_context():
            db.create_all()
            for (i, title) in enumerate(titles, 1):
                post = self.Post(title=title, content='content%d' % i)
                post.save()

    def tearDown(self):
        with self.app.test_request_context():
            db.drop_all()
            db.metadata.clear()
def test_create_filter_dsl():
    """Test request value extraction."""
    app = Flask('testapp')
    kwargs = MultiDict([('a', '1')])
    defs = dict(
        type=terms_filter('type.type'),
        subtype=terms_filter('type.subtype'),
    )

    with app.test_request_context(u'?type=a&type=b&subtype=c&type=zażółcić'):
        filters, args = _create_filter_dsl(kwargs, defs)
        assert len(filters) == 2
        assert args == MultiDict([
            ('a', u'1'),
            ('type', u'a'),
            ('type', u'b'),
            ('subtype', u'c'),
            ('type', u'zażółcić')
        ])

    kwargs = MultiDict([('a', '1')])
    with app.test_request_context('?atype=a&atype=b'):
        filters, args = _create_filter_dsl(kwargs, defs)
        assert not filters
        assert args == kwargs
def test_sentry6():
    """Test Sentry 6."""
    from invenio_logging.sentry import InvenioLoggingSentry
    app = Flask('testapp')
    app.config.update(dict(
        SENTRY_DSN='http://user:pw@localhost/0',
        LOGGING_SENTRY_CLASS='invenio_logging.sentry6:Sentry6',
        SENTRY_USER_ATTRS=['name'],
        SECRET_KEY='CHANGEME',
    ))
    InvenioLoggingSentry(app)
    LoginManager(app)

    class User(UserMixin):
        def __init__(self, user_id, name):
            self.id = user_id
            self.name = name

    with app.test_request_context('/'):
        assert app.extensions['sentry'].get_user_info(request) == {}

    with app.test_request_context('/'):
        login_user(User(1, 'viggo'))
        assert app.extensions['sentry'].get_user_info(request) == {
            'id': '1',
            'name': 'viggo',
        }
 def test_non_blueprint_rest_error_routing(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restful.Api(blueprint)
     api.add_resource(HelloWorld(), '/hi', endpoint="hello")
     api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye")
     app = Flask(__name__)
     app.register_blueprint(blueprint, url_prefix='/blueprint')
     api2 = flask_restful.Api(app)
     api2.add_resource(HelloWorld(), '/hi', endpoint="hello")
     api2.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye")
     with app.test_request_context('/hi', method='POST'):
         assert_false(api._should_use_fr_error_handler())
         assert_true(api2._should_use_fr_error_handler())
         assert_false(api._has_fr_route())
         assert_true(api2._has_fr_route())
     with app.test_request_context('/blueprint/hi', method='POST'):
         assert_true(api._should_use_fr_error_handler())
         assert_false(api2._should_use_fr_error_handler())
         assert_true(api._has_fr_route())
         assert_false(api2._has_fr_route())
     api._should_use_fr_error_handler = Mock(return_value=False)
     api2._should_use_fr_error_handler = Mock(return_value=False)
     with app.test_request_context('/bye'):
         assert_false(api._has_fr_route())
         assert_true(api2._has_fr_route())
     with app.test_request_context('/blueprint/bye'):
         assert_true(api._has_fr_route())
         assert_false(api2._has_fr_route())
class PluginManagerGetPlugins(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['TESTING'] = True
        self.plugin_manager = PluginManager()
        self.plugin_manager.init_app(self.app)

    def test_get_enabled_plugins(self):
        with self.app.test_request_context():
            plugins = get_enabled_plugins()

        self.assertEquals(
            set(plugins),
            set(self.plugin_manager.plugins.values())
        )

    def test_get_all_plugins(self):
        with self.app.test_request_context():
            plugins = get_all_plugins()

        self.assertEquals(len(plugins), 3)

    def test_get_plugin(self):
        with self.app.test_request_context():
            plugin = get_plugin("test1")

        self.assertEquals(plugin, self.plugin_manager.plugins["test1"])

    def test_get_plugin_from_all(self):
        with self.app.test_request_context():
            plugin = get_plugin_from_all("test3")

        self.assertFalse(plugin.enabled)
Example #11
0
    def test_handle_smart_errors(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        view = flask_restful.Resource

        api.add_resource(view, '/foo', endpoint='bor')
        api.add_resource(view, '/fee', endpoint='bir')
        api.add_resource(view, '/fii', endpoint='ber')

        with app.test_request_context("/faaaaa"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data.decode(), dumps({
                "message": NotFound.description,
            }) + "\n")

        with app.test_request_context("/fOo"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertTrue('did you mean /foo ?' in resp.data.decode())

        app.config['ERROR_404_HELP'] = False

        with app.test_request_context("/fOo"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data.decode(), dumps({
                "message": NotFound.description
            }) + "\n")
Example #12
0
def gen_app(config):
    """Generate a fresh app."""
    app = Flask('testapp')
    app.testing = True
    app.config.update(**config)

    FlaskCLI(app)
    FlaskMenu(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)
    FlaskOAuth(app)
    InvenioOAuthClient(app)

    app.register_blueprint(blueprint_client)
    app.register_blueprint(blueprint_settings)

    with app.app_context():
        db.create_all()

    app.test_request_context().push()

    datastore = app.extensions['invenio-accounts'].datastore

    datastore.create_user(
        email="existing@invenio-software.org", password='tester', active=True)
    datastore.create_user(
        email="test2@invenio-software.org", password='tester', active=True)
    datastore.create_user(
        email="test3@invenio-software.org", password='tester', active=True)
    datastore.commit()

    return app
Example #13
0
    def test_handle_smart_errors(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        view = flask_restful.Resource

        exception = Mock()
        exception.code = 404
        exception.data = {"status": 404, "message": "Not Found"}
        api.add_resource(view, '/foo', endpoint='bor')
        api.add_resource(view, '/fee', endpoint='bir')
        api.add_resource(view, '/fii', endpoint='ber')


        with app.test_request_context("/faaaaa"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data, dumps({
                "status": 404, "message": "Not Found",
            }))

        with app.test_request_context("/fOo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data, dumps({
                "status": 404, "message": "Not Found. You have requested this URI [/fOo] but did you mean /foo ?",
            }))

        with app.test_request_context("/fOo"):
            del exception.data["message"]
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data, dumps({
                "status": 404, "message": "You have requested this URI [/fOo] but did you mean /foo ?",
            }))
Example #14
0
class TestCoasterViews(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        load_config_from_file(self.app, "settings.py")
        self.app.add_url_rule('/', 'index', index)
        self.app.add_url_rule('/', 'external', external)

    def test_get_current_url(self):
        with self.app.test_request_context('/'):
            self.assertEqual(get_current_url(), '/')

        with self.app.test_request_context('/?q=hasgeek'):
            self.assertEqual(get_current_url(), '/?q=hasgeek')

    def test_get_next_url(self):
        with self.app.test_request_context('/?next=http://example.com'):
            self.assertEqual(get_next_url(external=True), 'http://example.com')
            self.assertEqual(get_next_url(), '/')
            self.assertEqual(get_next_url(default=()), ())
        
        with self.app.test_request_context('/'):
            session['next'] = '/external'
            self.assertEqual(get_next_url(session=True), '/external')

    def test_jsonp(self):
        with self.app.test_request_context('/?callback=callback'):
            kwargs = {'lang': 'en-us', 'query': 'python'}
            r = jsonp(**kwargs)
            response = 'callback({\n  "%s": "%s",\n  "%s": "%s"\n});' % ('lang', kwargs['lang'], 'query', kwargs['query'])
            self.assertEqual(response, r.data)

        with self.app.test_request_context('/'):
            param1, param2 = 1, 2
            r = jsonp(param1=param1, param2=param2)
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
            r = jsonp({'param1': param1, 'param2': param2})
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
            r = jsonp([('param1', param1), ('param2', param2)])
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)

    def test_requestargs(self):
        with self.app.test_request_context('/?p3=1&p3=2&p2=3&p1=1'):
            self.assertEqual(f(), (u'1', 3, [1, 2]))

        with self.app.test_request_context('/?p2=2'):
            self.assertEqual(f(p1='1'), (u'1', 2, None))

        with self.app.test_request_context('/?p3=1&p3=2&p2=3&p1=1'):
            self.assertEqual(f1(), (u'1', 3, [u'1', u'2']))

        with self.app.test_request_context('/?p2=2&p4=4'):
            self.assertRaises(TypeError, f, p4='4')
            self.assertRaises(BadRequest, f, p4='4')
Example #15
0
    def test_endpoints(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        api.add_resource(HelloWorld, '/ids/<int:id>', endpoint="hello")
        with app.test_request_context('/foo'):
            self.assertFalse(api._has_fr_route())

        with app.test_request_context('/ids/3'):
            self.assertTrue(api._has_fr_route())
def test_upload_field():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, 'test1.txt')
        safe_delete(path, 'test2.txt')

    class TestForm(form.BaseForm):
        upload = form.FileUploadField('Upload', path=path)

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.path, path)

    _remove_testfiles()

    dummy = Dummy()

    # Check upload
    with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 1'), 'test1.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'test1.txt')
        ok_(op.exists(op.join(path, 'test1.txt')))

    # Check replace
    with app.test_request_context(method='POST', data={'upload': (BytesIO(b'Hello World 2'), 'test2.txt')}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())
        my_form.populate_obj(dummy)

        eq_(dummy.upload, 'test2.txt')
        ok_(not op.exists(op.join(path, 'test1.txt')))
        ok_(op.exists(op.join(path, 'test2.txt')))

    # Check delete
    with app.test_request_context(method='POST', data={'_upload-delete': 'checked'}):
        my_form = TestForm(helpers.get_form_data())

        ok_(my_form.validate())

        my_form.populate_obj(dummy)
        eq_(dummy.upload, None)

        ok_(not op.exists(op.join(path, 'test2.txt')))
Example #17
0
class TestSelf(object):

    def setup(self):
        self.app = Flask(__name__)

    def test_only_valid_link_attrs_set(self):
        with self.app.test_request_context():
            l = Self(foo='foo', name='foo')

            assert not hasattr(l, 'foo')
            assert l.name == 'foo'

    def test_to_dict(self):
        with self.app.test_request_context():
            l = Self(foo='foo', name='foo')

            expected = {
                'self': {
                    'href': '/',
                    'name': 'foo',
                }
            }

            assert l.to_dict() == expected

    def test_to_json(self):
        with self.app.test_request_context():
            l = Self(foo='foo', name='foo')

            expected = json.dumps({
                'self': {
                    'href': '/',
                    'name': 'foo',
                }
            })

            assert l.to_json() == expected

    def test_with_server_name(self):
        self.app.config['SERVER_NAME'] = 'foo.com'
        with self.app.test_request_context():
            l = Self(foo='foo', name='foo')

            expected = {
                'self': {
                    'href': 'http://foo.com/',
                    'name': 'foo',
                }
            }

            assert l.to_dict() == expected
Example #18
0
def base_app(request):
    """Flask application fixture without OAuthClient initialized."""
    instance_path = tempfile.mkdtemp()
    base_app = Flask('testapp')
    base_app.config.update(
        TESTING=True,
        WTF_CSRF_ENABLED=False,
        LOGIN_DISABLED=False,
        CACHE_TYPE='simple',
        OAUTHCLIENT_REMOTE_APPS=dict(
            orcid=REMOTE_APP,
        ),
        ORCID_APP_CREDENTIALS=dict(
            consumer_key='changeme',
            consumer_secret='changeme',
        ),
        # use local memory mailbox
        EMAIL_BACKEND='flask_email.backends.locmem.Mail',
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite://'),
        SERVER_NAME='localhost',
        DEBUG=False,
        SECRET_KEY='TEST',
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
    )
    FlaskCLI(base_app)
    FlaskMenu(base_app)
    Babel(base_app)
    Mail(base_app)
    InvenioDB(base_app)
    InvenioAccounts(base_app)

    with base_app.app_context():
        if str(db.engine.url) != 'sqlite://' and \
           not database_exists(str(db.engine.url)):
                create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with base_app.app_context():
            db.session.close()
            if str(db.engine.url) != 'sqlite://':
                drop_database(str(db.engine.url))
            shutil.rmtree(instance_path)

    request.addfinalizer(teardown)

    base_app.test_request_context().push()

    return base_app
Example #19
0
    def test_get_request_body_args(self):
        """
        Tests getting the request body args
        from a flask request object.
        """
        app = Flask('myapp')
        body = dict(x=1)
        with app.test_request_context('/', data=json.dumps(body), content_type='application/json'):
            q, b = get_request_query_body_args(request)
            self.assertDictEqual(b, body)

        with app.test_request_context('/', data=body):  # Form encoded
            q, b = get_request_query_body_args(request)
            self.assertDictEqual(b, dict(x=['1']))
Example #20
0
def test_context_local():
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    jbp1 = make_jira_blueprint(
        "https://t1.atlassian.com", "foo1", "bar1", redirect_to="url1"
    )
    app1.register_blueprint(jbp1)

    app2 = Flask(__name__)
    jbp2 = make_jira_blueprint(
        "https://t2.atlassian.com", "foo2", "bar2", redirect_to="url2"
    )
    app2.register_blueprint(jbp2)

    # outside of a request context, referencing functions on the `jira` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        jira.get("https://google.com")

    # inside of a request context, `jira` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        jbp1.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig1")
        jbp2.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig2")

        app1.preprocess_request()
        jira.get("https://google.com")
        auth_header = dict(
            parse_authorization_header(
                responses.calls[0].request.headers["Authorization"].decode("utf-8")
            )
        )
        assert auth_header["oauth_consumer_key"] == "foo1"
        assert auth_header["oauth_signature"] == "sig1"

    with app2.test_request_context("/"):
        jbp1.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig1")
        jbp2.session.auth.client.get_oauth_signature = mock.Mock(return_value="sig2")

        app2.preprocess_request()
        jira.get("https://google.com")
        auth_header = dict(
            parse_authorization_header(
                responses.calls[1].request.headers["Authorization"].decode("utf-8")
            )
        )
        assert auth_header["oauth_consumer_key"] == "foo2"
        assert auth_header["oauth_signature"] == "sig2"
Example #21
0
    def test_base_url(self):
        """
        Tests that the base_url always returns the
        correct shit.
        """
        app = Flask('myapp')
        d = FlaskDispatcher(app)

        with app.test_request_context():
            self.assertEqual(d.base_url, 'http://localhost/')

        d = FlaskDispatcher(app, url_prefix='someprefix', auto_options_name='Options2')
        with app.test_request_context():
            self.assertEqual(d.base_url, 'http://localhost/someprefix')
Example #22
0
class SwaggerBenchmark(Benchmark):
    '''Swagger serialization benchmark for a full API'''
    times = 1000

    def before_class(self):
        self.app = Flask(__name__)
        api.init_app(self.app)

    def bench_swagger_specs(self):
        with self.app.test_request_context('/'):
            return Swagger(api).as_dict()

    def bench_swagger_specs_cached(self):
        with self.app.test_request_context('/'):
            return api.__schema__
class RuleTestCase(unittest.TestCase):

    def setUp(self):
        # create a new app for every test
        self.app = Flask(__name__)

    def _make_rule(self, **kwargs):
        def vf():
            return {}

        return Rule(
            kwargs.get('routes', ['/', ]),
            kwargs.get('methods', ['GET', ]),
            kwargs.get('view_func_or_data', vf),
            kwargs.get('renderer', json_renderer),
            kwargs.get('view_kwargs'),
        )

    def test_rule_single_route(self):
        r = self._make_rule(routes='/')
        assert_equal(r.routes, ['/', ])

    def test_rule_single_method(self):
        r = self._make_rule(methods='GET')
        assert_equal(r.methods, ['GET', ])

    def test_rule_lambda_view(self):
        r = self._make_rule(view_func_or_data=lambda: '')
        assert_true(callable(r.view_func_or_data))

    def test_url_for_simple(self):
        r = Rule(['/project/'], 'get', view_func_or_data=dummy_view, renderer=json_renderer)
        process_rules(self.app, [r])
        with self.app.test_request_context():
            assert_equal(url_for('JSONRenderer__dummy_view'), '/project/')

    def test_url_for_with_argument(self):
        r = Rule(['/project/<pid>/'], 'get', view_func_or_data=dummy_view2, renderer=json_renderer)
        process_rules(self.app, [r])
        with self.app.test_request_context():
            assert_equal(url_for('JSONRenderer__dummy_view2', pid=123), '/project/123/')

    def test_url_for_with_prefix(self):
        api_rule = Rule(['/project/'], 'get', view_func_or_data=dummy_view3,
                renderer=json_renderer)
        process_rules(self.app, [api_rule], prefix='/api/v1')
        with self.app.test_request_context():
            assert_equal(url_for('JSONRenderer__dummy_view3'), '/api/v1/project/')
Example #24
0
class TestCase(unittest.TestCase):

    TESTING = True
    MAIL_DEFAULT_SENDER = "support@mysite.com"

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config.from_object(self)
        self.assertTrue(self.app.testing)
        self.mail = Mail(self.app)
        self.ctx = self.app.test_request_context()
        self.ctx.push()

    def tearDown(self):
        self.ctx.pop()

    def assertIn(self, member, container, msg=None):
        if hasattr(unittest.TestCase, "assertIn"):
            return unittest.TestCase.assertIn(self, member, container, msg)
        return self.assertTrue(member in container)

    def assertNotIn(self, member, container, msg=None):
        if hasattr(unittest.TestCase, "assertNotIn"):
            return unittest.TestCase.assertNotIn(self, member, container, msg)
        return self.assertFalse(member in container)

    def assertIsNone(self, obj, msg=None):
        if hasattr(unittest.TestCase, "assertIsNone"):
            return unittest.TestCase.assertIsNone(self, obj, msg)
        return self.assertTrue(obj is None)

    def assertIsNotNone(self, obj, msg=None):
        if hasattr(unittest.TestCase, "assertIsNotNone"):
            return unittest.TestCase.assertIsNotNone(self, obj, msg)
        return self.assertTrue(obj is not None)
Example #25
0
    def test_url_absolute(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", absolute=True)

        with app.test_request_context("/"):
            self.assertEquals("http://localhost/3", field.output("hey", Foo()))
Example #26
0
    def test_url_invalid_object(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar")

        with app.test_request_context("/"):
            self.assertRaises(MarshallingException, lambda: field.output("hey", None))
Example #27
0
class InitializationTestCase(unittest.TestCase):
    ''' Tests the two initialization methods '''

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = '1234'

    def test_init_app(self):
        login_manager = LoginManager()
        login_manager.init_app(self.app, add_context_processor=True)

        self.assertIsInstance(login_manager, LoginManager)

    def test_class_init(self):
        login_manager = LoginManager(self.app, add_context_processor=True)

        self.assertIsInstance(login_manager, LoginManager)

    def test_login_disabled_is_set(self):
        login_manager = LoginManager(self.app, add_context_processor=True)
        self.assertFalse(login_manager._login_disabled)

    def test_no_user_loader_raises(self):
        login_manager = LoginManager(self.app, add_context_processor=True)
        with self.app.test_request_context():
            session['user_id'] = '2'
            with self.assertRaises(Exception) as cm:
                login_manager.reload_user()
            expected_exception_message = 'No user_loader has been installed'
            self.assertTrue(
                str(cm.exception).startswith(expected_exception_message))
Example #28
0
class SecretKeyTestCase(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)

    def test_bytes(self):
        self.app.config['SECRET_KEY'] = b'\x9e\x8f\x14'
        with self.app.test_request_context():
            self.assertEqual(_secret_key(), b'\x9e\x8f\x14')

    def test_native(self):
        self.app.config['SECRET_KEY'] = '\x9e\x8f\x14'
        with self.app.test_request_context():
            self.assertEqual(_secret_key(), b'\x9e\x8f\x14')

    def test_default(self):
        self.assertEqual(_secret_key('\x9e\x8f\x14'), b'\x9e\x8f\x14')
Example #29
0
 def test_resource_resp(self):
     app = Flask(__name__)
     resource = flask_restful.Resource()
     resource.get = Mock()
     with app.test_request_context("/foo"):
         resource.get.return_value = flask.make_response('')
         resource.dispatch_request()
Example #30
0
    def test_media_types(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo",
            headers={'Accept': 'application/json'}):
            self.assertEquals(api.mediatypes(), ['application/json'])