Beispiel #1
1
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_bitbucket_blueprint(
        "foo1", "bar1", redirect_to="url1", backend=MemoryBackend({"access_token": "app1"})
    )
    app1.register_blueprint(ghbp1)

    app2 = Flask(__name__)
    ghbp2 = make_bitbucket_blueprint(
        "foo2", "bar2", redirect_to="url2", backend=MemoryBackend({"access_token": "app2"})
    )
    app2.register_blueprint(ghbp2)

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

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

    with app2.test_request_context("/"):
        app2.preprocess_request()
        bitbucket.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Beispiel #2
1
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_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_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.decode(), 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.decode(),
                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.decode(),
                dumps({"status": 404, "message": "You have requested this URI [/fOo] but did you mean /foo ?"}),
            )
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
    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")
Beispiel #7
1
 def test_renderer(self, **kwargs):
     app = Flask(__name__)
     app.template_folder = os.path.join(self.root, "templates")
     app.config.update(MAKO_CACHE_DIR=os.path.join(self.root, "cache"), MAKO_CACHE_SIZE=10)
     app.config.update(kwargs)
     with app.test_request_context():
         yield app, MakoTemplates(app)
Beispiel #8
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",
        )
Beispiel #9
1
class TestCase(unittest.TestCase):
    """An helper mixin for common operations"""

    def setUp(self):
        """Initialize an Flask application"""
        self.app = Flask(__name__)

    @contextmanager
    def context(self):
        with self.app.test_request_context("/"):
            yield

    def get_specs(self, prefix="/api", app=None, status=200):
        """Get a Swagger specification for a RestPlus API"""
        with self.app.test_client() as client:
            response = client.get("{0}/swagger.json".format(prefix))
            self.assertEquals(response.status_code, status)
            self.assertEquals(response.content_type, "application/json")
            return json.loads(response.data.decode("utf8"))

    def get_declaration(self, namespace="default", prefix="/api", status=200, app=None):
        """Get an API declaration for a given namespace"""
        with self.app.test_client() as client:
            response = client.get("{0}/swagger.json".format(prefix, namespace))
            self.assertEquals(response.status_code, status)
            self.assertEquals(response.content_type, "application/json")
            return json.loads(response.data.decode("utf8"))

    def get_json(self, url, status=200):
        with self.app.test_client() as client:
            response = client.get(url)

        self.assertEquals(response.status_code, status)
        self.assertEquals(response.content_type, "application/json")
        return json.loads(response.data.decode("utf8"))
Beispiel #10
1
    def test_url(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.assertEquals("/3", field.output("hey", Foo()))
Beispiel #11
1
    def test_handle_error_signal(self):
        if not signals_available:
            # This test requires the blinker lib to run.
            print("Can't test signals without signal support")
            return
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 400
        exception.data = {"foo": "bar"}

        recorded = []

        def record(sender, exception):
            recorded.append(exception)

        got_request_exception.connect(record, app)
        try:
            with app.test_request_context("/foo"):
                api.handle_error(exception)
                self.assertEquals(len(recorded), 1)
                self.assertTrue(exception is recorded[0])
        finally:
            got_request_exception.disconnect(record, app)
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
Beispiel #13
0
    def test_apply_all_method_decorators_if_not_mapping(self):
        def upper_deco(f):
            def upper(*args, **kwargs):
                return f(*args, **kwargs).upper()

            return upper

        class TestResource(flask_restful.Resource):
            method_decorators = [upper_deco]

            def get(self):
                return "get test"

            def post(self):
                return "post test"

        app = Flask(__name__)

        with app.test_request_context("/", method="POST"):
            r = TestResource().dispatch_request()
            assert r == "POST TEST"

        with app.test_request_context("/", method="GET"):
            r = TestResource().dispatch_request()
            assert r == "GET TEST"
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)
    def test_non_blueprint_non_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")

        @app.route("/hi")
        def hi():
            return "hi"

        @app.route("/bye")
        def bye():
            flask.abort(404)

        with app.test_request_context("/hi", method="POST"):
            assert_false(api._should_use_fr_error_handler())
            assert_false(api._has_fr_route())
        with app.test_request_context("/blueprint/hi", method="POST"):
            assert_true(api._should_use_fr_error_handler())
            assert_true(api._has_fr_route())
        api._should_use_fr_error_handler = Mock(return_value=False)
        with app.test_request_context("/bye"):
            assert_false(api._has_fr_route())
        with app.test_request_context("/blueprint/bye"):
            assert_true(api._has_fr_route())
Beispiel #16
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", base_path=path)

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_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")))
Beispiel #18
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"]))
Beispiel #19
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")
    def _create_noext(self, rule=None, view_func=None, safe_domains=[], add_jinja_filters=True):
        self.noext_url = "/test-ext-url-handler"

        app = Flask(__name__)
        app.config["TESTING"] = True
        app.test_request_context().push()
        client = app.test_client()

        if not rule:
            rule = "%s/<path:url>" % self.noext_url

        noext = NoExtRef(
            app, rule=rule, view_func=view_func, safe_domains=safe_domains, add_jinja_filters=add_jinja_filters
        )
        return (client, noext)
class TestUser(unittest.TestCase):
    def setUp(self):
        self.application = Flask(__name__)
        self.application.config["TESTING"] = True
        settings.EQ_SERVER_SIDE_STORAGE = True

    def test_get_user_id(self):
        with self.application.test_request_context():
            user = User("1", "2")
            self.assertEquals("1", user.user_id)

    def test_get_user_ik(self):
        with self.application.test_request_context():
            user = User("1", "2")
            self.assertEquals("2", user.user_ik)
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__
Beispiel #23
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))
Beispiel #24
0
def get_app(settings=None, extensions=None, add_default_extensions=True, *args, **kwargs):
    reset_db = None
    if "reset_db" in kwargs:
        reset_db = kwargs.pop("reset_db")
    app = Flask(__name__, *args, **kwargs)
    if settings is not None:
        app.config.from_object(settings)
    else:
        raise NoSettingsObjectError
    if extensions:
        for e in extensions:
            e.init_app(app)
    if reset_db is not None:
        with app.test_request_context():
            models.BaseMixin.metadata.bind = models.BaseMixin.engine
            models.BaseMixin.engine.echo = True
            models.BaseMixin.metadata.drop_all(checkfirst=True)
            models.BaseMixin.metadata.create_all(checkfirst=True)
    if add_default_extensions:
        router = FlaskRouter(app)
        apps = FlaskApps(app)
        # loader = FlaskTemplateLoader(app)

    app.jinja_env.globals["assets"] = assets
    app.jinja_env.filters["date_pretty"] = date_pretty

    # @app.after_request
    # def af(res):
    #    print request.environ['eventlet.input']
    #    return res

    return app
Beispiel #25
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()
Beispiel #26
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)
Beispiel #27
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")
def test_relative_path():
    app = Flask(__name__)

    path = _create_temp()

    def _remove_testfiles():
        safe_delete(path, "test1.txt")

    class TestForm(form.BaseForm):
        upload = form.FileUploadField("Upload", base_path=path, relative_path="inner/")

    class Dummy(object):
        pass

    my_form = TestForm()
    eq_(my_form.upload.base_path, path)
    eq_(my_form.upload.relative_path, "inner/")

    _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, "inner/test1.txt")
        ok_(op.exists(op.join(path, "inner/test1.txt")))

        eq_(url_for("static", filename=dummy.upload), "/static/inner/test1.txt")
Beispiel #29
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))
class PointOfInterestSearchEndpointTest(unittest.TestCase):
    def setUp(self):
        self._poi_service = Mock()
        self._poi_service.name_search = Mock(return_value=[])

        self._app = Flask(__name__)
        self._endpoint = PointOfInterestSearchEndpoint("test", self._poi_service)
        self._app.add_url_rule("/search", "test.search", self._endpoint.get)
        self._app.add_url_rule("/<slug>", "test.poi", self._endpoint.get)

    def test_making_search_passes_it_to_service(self):
        self._poi_service.search_name.return_value = []
        search_terms = "test search"
        self._make_search_request(search_terms)
        self._poi_service.search_name.assert_called_once_with(search_terms)

    def test_return_value_from_service_is_serialised_to_json(self):
        self._poi_service.search_name.return_value = [PointOfInterest(slug="test:test")]
        response = self._make_search_request("test")
        self.assertEquals("test:test", response["results"][0]["poi"]["slug"])

    def _make_search_request(self, search_terms):
        with self._app.test_request_context(
            "/search?q={q}".format(q=quote_plus(search_terms)), headers=[("Accept", "application/json")]
        ):
            response = self._endpoint.get()
        return json.loads(response.data)