Example #1
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"))
Example #2
1
 def testGetTpls(self):
     app = Flask(__name__)
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?which=asdfjdskfjs")
         self.assertEquals(
             statserv.server.send_error(request, "template does" " not exist"),
             statserv.server.get_tpls(),
             "The get_tpls method really shouldn't try to send " "back a template for 'asdfjdskfjs.'",
         )
     tplsempty = False
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?which=")
         tplsempty = statserv.server.get_tpls()
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?which=all")
         self.assertEquals(
             statserv.server.get_tpls(),
             tplsempty,
             "The get_tpls method should send back all " "templates on both which=all and which=.",
         )
     with app.test_client() as c:
         testRequest = c.get("/tpls.json?callback=blah" "&which=header&which=home")
         header = open(statserv.server.determine_path() + "/tpls/header.tpl").read()
         home = open(statserv.server.determine_path() + "/tpls/home.tpl").read()
         response = statserv.server.make_response("blah", dict({"header": header, "home": home}))
         self.assertEquals(
             statserv.server.get_tpls(),
             response,
             "The single-template support does not seem to be " "working properly.",
         )
Example #3
1
class OriginsW3TestCase(FlaskCorsTestCase):
    def setUp(self):
        self.app = Flask(__name__)

        @self.app.route("/")
        @cross_origin(origins="*", send_wildcard=False, always_send=False)
        def allowOrigins():
            """ This sets up flask-cors to echo the request's `Origin` header,
                only if it is actually set. This behavior is most similar to the
                actual W3 specification, http://www.w3.org/TR/cors/ but
                is not the default because it is more common to use the wildcard
                approach.
            """
            return "Welcome!"

    def test_wildcard_origin_header(self):
        """ If there is an Origin header in the request, the Access-Control-Allow-Origin
            header should be echoed back.
        """
        example_origin = "http://example.com"
        with self.app.test_client() as c:
            for verb in self.iter_verbs(c):
                result = verb("/", headers={"Origin": example_origin})
                self.assertEqual(result.headers.get(AccessControlAllowOrigin), example_origin)

    def test_wildcard_no_origin_header(self):
        """ If there is no Origin header in the request, the Access-Control-Allow-Origin
            header should not be included.
        """
        with self.app.test_client() as c:
            for verb in self.iter_verbs(c):
                result = verb("/")
                self.assertTrue(AccessControlAllowOrigin not in result.headers)
class SupportsCredentialsCase(FlaskCorsTestCase):
    def setUp(self):
        self.app = Flask(__name__)

        @self.app.route("/test_credentials")
        @cross_origin(supports_credentials=True)
        def test_credentials():
            return "Credentials!"

        @self.app.route("/test_open")
        @cross_origin()
        def test_open():
            return "Open!"

    def test_credentialed_request(self):
        """ The specified route should return the
            Access-Control-Allow-Credentials header.
        """
        with self.app.test_client() as c:
            result = c.get("/test_credentials")
            header = result.headers.get(ACL_CREDENTIALS)
            self.assertEquals(header, "true")

    def test_open_request(self):
        """ The default behavior should be to disallow credentials.
        """
        with self.app.test_client() as c:
            result = c.get("/test_open")
            self.assertTrue(ACL_CREDENTIALS not in result.headers)
Example #5
1
    def testGetEvent(self):
        app = Flask(__name__)
        conn = Connection()
        dbname = "test_db"
        db = conn[dbname]
        with app.test_client() as c:
            testRequest = c.get("/event.json?callback=blah")
            self.assertEquals(
                statserv.server.send_error(
                    request, "need to know what" " event you want to " "complete this" " request"
                ),
                statserv.server.get_event(),
                "The get_event method needs to error out if " "no event id is passed to it.",
            )

        with app.test_client() as c:
            statserv.server.database = conn[dbname]
            testRequest = c.get("/event.json?callback=blah&id=test2011")
            expected = statserv.server.send_error(request, "that event does not seem to exist....")
            self.assertEquals(
                expected,
                statserv.server.get_event(),
                "The get_event method should error out if " "the requested event doesn't exist.",
            )

        with app.test_client() as c:
            statserv.server.database = conn[dbname]
            expectdict = dict({"id": "test2011", "descr": "Testing stuff"})
            db.stattrtbls.insert(expectdict)
            testRequest = c.get("/event.json?callback=blah" "&id=test2011&results=false")
            del expectdict["_id"]
            expected = statserv.server.make_response("blah", dict({"table": expectdict}))
            actual = statserv.server.get_event()
            db.stattrtbls.remove({})
            self.assertEquals(
                expected,
                actual,
                "The server should not return results from the " "get_event method when results=false.",
            )

        with app.test_client() as c:
            testRequest = c.get("/event.json?callback=blah" "&id=test2011")
            expecttbl = dict({u"id": u"test2011", u"descr": u"Testing stuff"})
            db.stattrtbls.insert(expecttbl)
            expectres = dict({u"participants": [u"test1", u"test2"], u"score": [22, 25], u"victory": [False, True]})
            db["test2011"].insert(expectres)
            del expectres["_id"]
            del expecttbl["_id"]
            expectdict = dict({"events": [expectres], "table": expecttbl})
            expected = statserv.server.make_response("blah", expectdict)
            statserv.server.database = conn[dbname]
            actual = statserv.server.get_event()
            db.stattrtbls.remove({})
            db.drop_collection("test2011")
            self.assertEquals(
                expected,
                actual,
                "The get_event method somehow returned something " "different from what we explicitly gave it.",
            )
class UserAPITestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        self.app = Flask(__name__)
        self.app.secret_key = "test_key"
        # add an index rule because some views redirect to index
        self.app.add_url_rule("/", view_func=TestView.as_view("index", template="index.html"), methods=["GET", "POST"])
        self.app.add_url_rule(
            "/restricted/", view_func=RestrictedView.as_view("restricted", template="index.html"), methods=["GET"]
        )
        self.app.add_url_rule("/logout/", view_func=LoginAPI.logout)
        self.app.add_url_rule("/login/", view_func=LoginAPI.as_view("login"), methods=["GET", "POST"])
        self.app.add_url_rule("/delete/<user_id>/", view_func=UserAPI.as_view("user_api"), methods=["DELETE"])
        self.test_client = self.app.test_client()
        self.user = None
        super(UserAPITestCase, self).__init__(*args, **kwargs)

    def setUp(self):
        # nothing to do for set up
        self.user = DatabaseTestCase.add_user()

    def tearDown(self):
        # nothing to do for tear down
        self.user = DatabaseTestCase.delete_user()

    def login(self, password):
        return self.test_client.post(
            "/login/", data=dict(username="test_user", password=password), follow_redirects=True
        )

    def test_delete_user(self):
        """test setting a user to inactive through UserAPI.
		ensures that deletion only works when user is logged in."""
        with self.app.test_client() as c:
            # first check when user isn't logged in
            rv = c.delete("/delete/{0}/".format(self.user.id))
            assert User.objects(username="test_user")[0].active == True
            with c.session_transaction() as sess:
                sess["username"] = "test_user"
            rv = c.delete("/delete/{0}/".format(self.user.id))
            assert User.objects(username="test_user")[0].active == False

    def test_login(self):
        # good password works
        assert "OK" in self.login("test_password").data
        # bad password doesn't
        assert "error" in self.login("bad_password").data
        self.user.active = False
        self.user.save()
        # inactive users can't log in
        assert "error" in self.login("test_password").data

    def test_user_logout(self):
        rv = self.test_client.get("/logout/", follow_redirects=True)
        assert "OK" in rv.data

    def test_restricted_view(self):
        rv = self.test_client.get("/restricted/", follow_redirects=True)
        assert "not logged in" in rv.data
Example #7
1
 def testAddEvent(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get(
             "/event.json?activity=testing"
             "&variables=victory&types="
             "bool&officials=tester&descr=testing%20stuff&"
             "id=testing123&_username=tester&_session=1234"
         )
         expected = {
             "activity": "testing",
             "descr": "testing stuff",
             "fields": ["participants", "victory"],
             "types": ["varchar", "bool"],
             "officials": ["tester"],
             "id": "testing123",
             "rstarts": [],
             "checks": [],
             "rends": [],
         }
         db = conn.test_db
         statserv.server.database = conn.test_db
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.add_event(request)
         actual = db.stattrtbls.find_one({})
         del actual["_id"]
         self.assertEquals(
             expected,
             actual,
             "The add_event method added something other than "
             "what we expected. Expected: `%s`, "
             "actual: `%s`." % (expected, actual),
         )
         conn.drop_database("test_db")
Example #8
1
 def testAddResults(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get(
             "/results.json?_username=tester&_session=1234&"
             "_method=POST&results=tester&results=true&"
             "event=testing123"
         )
         event = {"id": "testing123", "fields": ["participants", "victory"], "types": ["varchar", "bool"]}
         db = conn.test_db
         db.stattrtbls.insert(event)
         del event["_id"]
         result = {"participants": ["tester"], "victory": [True]}
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.database = conn.test_db
         statserv.server.add_results()
         actual = db.testing123.find_one({})
         del actual["_id"]
         self.assertEquals(
             result,
             actual,
             "The add_results method did something we didn't "
             "expect. Expected: `%s`, actual: `%s`." % (result, actual),
         )
         conn.drop_database("test_db")
class LogicalAPINamingTestCase(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks

        def post_task(request):
            data = request.json
            self.tasks.append({"task": data["task"]})
            return {}, 201

        self.get_tasks = get_tasks
        self.post_task = post_task

    def test_naming_a_single_api(self):
        api_1 = Api(version="v1", name="read-only-methods")
        api_1.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/task/", handler=self.get_tasks))

        self.app.register_blueprint(api_1)
        self.app.config["TESTING"] = True

        client = self.app.test_client()
        resp = client.get("/v1/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers["Content-Type"], "application/json")

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(len(data), 2)

    def test_naming_multiple_logic_apis(self):
        api_1 = Api(version="v1", name="read-only-methods")
        api_1.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/task/", handler=self.get_tasks))

        self.app.register_blueprint(api_1)

        api_2 = Api(version="v1", name="write-methods")
        api_2.register_endpoint(ApiEndpoint(http_method="POST", endpoint="/task/", handler=self.post_task))
        self.app.register_blueprint(api_2)
        self.app.config["TESTING"] = True

        client = self.app.test_client()

        # Testing GET
        resp = client.get("/v1/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.headers["Content-Type"], "application/json")

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(len(data), 2)

        # Testing POST
        resp = client.post("/v1/task/", content_type="application/json", data=json.dumps({"task": "New Task!"}))

        self.assertEqual(resp.status_code, 201)
        self.assertEqual(resp.headers["Content-Type"], "application/json")
        self.assertEqual(len(self.tasks), 3)
Example #10
0
def test_modal_edit():
    # bootstrap 2 - test edit_modal
    app_bs2 = Flask(__name__)
    admin_bs2 = Admin(app_bs2, template_mode="bootstrap2")

    class EditModalOn(fileadmin.FileAdmin):
        edit_modal = True
        editable_extensions = ("txt",)

    class EditModalOff(fileadmin.FileAdmin):
        edit_modal = False
        editable_extensions = ("txt",)

    path = op.join(op.dirname(__file__), "files")
    edit_modal_on = EditModalOn(path, "/files/", endpoint="edit_modal_on")
    edit_modal_off = EditModalOff(path, "/files/", endpoint="edit_modal_off")

    admin_bs2.add_view(edit_modal_on)
    admin_bs2.add_view(edit_modal_off)

    client_bs2 = app_bs2.test_client()

    # bootstrap 2 - ensure modal window is added when edit_modal is enabled
    rv = client_bs2.get("/admin/edit_modal_on/")
    eq_(rv.status_code, 200)
    data = rv.data.decode("utf-8")
    ok_("fa_modal_window" in data)

    # bootstrap 2 - test edit modal disabled
    rv = client_bs2.get("/admin/edit_modal_off/")
    eq_(rv.status_code, 200)
    data = rv.data.decode("utf-8")
    ok_("fa_modal_window" not in data)

    # bootstrap 3
    app_bs3 = Flask(__name__)
    admin_bs3 = Admin(app_bs3, template_mode="bootstrap3")

    admin_bs3.add_view(edit_modal_on)
    admin_bs3.add_view(edit_modal_off)

    client_bs3 = app_bs3.test_client()

    # bootstrap 3 - ensure modal window is added when edit_modal is enabled
    rv = client_bs3.get("/admin/edit_modal_on/")
    eq_(rv.status_code, 200)
    data = rv.data.decode("utf-8")
    ok_("fa_modal_window" in data)

    # bootstrap 3 - test modal disabled
    rv = client_bs3.get("/admin/edit_modal_off/")
    eq_(rv.status_code, 200)
    data = rv.data.decode("utf-8")
    ok_("fa_modal_window" not in data)
Example #11
0
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

    @contextmanager
    def settings(self, **settings):
        """
        A context manager to alter app settings during a test and restore it after..
        """
        original = {}

        # backup
        for key, value in settings.items():
            original[key] = self.app.config.get(key)
            self.app.config[key] = value

        yield

        # restore
        for key, value in original.items():
            self.app.config[key] = value

    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"))
Example #12
0
    def setUp(self):

        self.cookbook = API("cookbook", "http://localhost:8881/api")

        @self.cookbook.action
        def cabbage(spicy, capitalize=False):
            if spicy:
                c = "kimchi"
            else:
                c = "sauerkraut"
            if capitalize:
                return c.capitalize()
            else:
                return c

        @self.cookbook.action
        def pounds_to_kilos(pounds):
            if pounds > 100:
                raise APIError("Too many pounds", http_code=501)
            return 0.453592 * pounds * pounds / pounds

        @self.cookbook.action
        def noop():
            return None

        api.apio_index = RemoteAPI(index_spec)

        with patch.object(requests, "post") as mock_post:
            # Load API
            mock_post.return_value.status_code = 200
            mock_post.return_value.json = cookbook_spec
            from apio.index import cookbook as remote_cookbook

            self.remote_cookbook = remote_cookbook
            mock_post.assert_called_with(
                "http://api.apio.io/actions/get_spec",
                headers={"Content-Type": "application/json"},
                data=json.dumps("cookbook"),
            )

        # Create test client for some HTTP tests
        from flask import Flask

        app = Flask(__name__, static_folder=None)
        app.register_blueprint(self.cookbook.get_blueprint(), url_prefix="/api")
        self.werkzeug_client = app.test_client()

        # Test debug mode
        app = Flask(__name__, static_folder=None)
        app.config["PROPAGATE_EXCEPTIONS"] = True
        app.register_blueprint(self.cookbook.get_blueprint(debug=True), url_prefix="/api")
        self.werkzeug_client_debug = app.test_client()
Example #13
0
def test_bugsnag_crash(deliver):
    app = Flask("bugsnag")

    @app.route("/hello")
    def hello():
        raise SentinalError("oops")

    handle_exceptions(app)
    app.test_client().get("/hello")

    eq_(deliver.call_count, 1)
    payload = deliver.call_args[0][0]
    eq_(payload["events"][0]["exceptions"][0]["errorClass"], "test_flask.SentinalError")
    eq_(payload["events"][0]["metaData"]["request"]["url"], "http://localhost/hello")
Example #14
0
    def test_bugsnag_crash(self):
        app = Flask("bugsnag")

        @app.route("/hello")
        def hello():
            raise SentinelError("oops")

        handle_exceptions(app)
        app.test_client().get("/hello")

        self.assertEqual(1, len(self.server.received))
        payload = self.server.received[0]["json_body"]
        self.assertEqual(payload["events"][0]["exceptions"][0]["errorClass"], "test_flask.SentinelError")
        self.assertEqual(payload["events"][0]["metaData"]["request"]["url"], "http://localhost/hello")
Example #15
0
def test_bugsnag_notify(deliver):
    app = Flask("bugsnag")

    @app.route("/hello")
    def hello():
        bugsnag.notify(SentinalError("oops"))
        return "OK"

    handle_exceptions(app)
    app.test_client().get("/hello")

    eq_(deliver.call_count, 1)
    payload = deliver.call_args[0][0]
    eq_(payload["events"][0]["metaData"]["request"]["url"], "http://localhost/hello")
Example #16
0
    def test_bugsnag_notify(self):
        app = Flask("bugsnag")

        @app.route("/hello")
        def hello():
            bugsnag.notify(SentinelError("oops"))
            return "OK"

        handle_exceptions(app)
        app.test_client().get("/hello")

        self.assertEqual(1, len(self.server.received))
        payload = self.server.received[0]["json_body"]
        self.assertEqual(payload["events"][0]["metaData"]["request"]["url"], "http://localhost/hello")
    def test_multiple_apps(self):
        app1 = Flask("app1")
        app2 = Flask("app2")

        limiter = Limiter(global_limits=["1/second"])
        limiter.init_app(app1)
        limiter.init_app(app2)

        @app1.route("/ping")
        def ping():
            return "PONG"

        @app1.route("/slowping")
        @limiter.limit("1/minute")
        def slow_ping():
            return "PONG"

        @app2.route("/ping")
        @limiter.limit("2/second")
        def ping_2():
            return "PONG"

        @app2.route("/slowping")
        @limiter.limit("2/minute")
        def slow_ping_2():
            return "PONG"

        with hiro.Timeline().freeze() as timeline:
            with app1.test_client() as cli:
                self.assertEqual(cli.get("/ping").status_code, 200)
                self.assertEqual(cli.get("/ping").status_code, 429)
                timeline.forward(1)
                self.assertEqual(cli.get("/ping").status_code, 200)
                self.assertEqual(cli.get("/slowping").status_code, 200)
                timeline.forward(59)
                self.assertEqual(cli.get("/slowping").status_code, 429)
                timeline.forward(1)
                self.assertEqual(cli.get("/slowping").status_code, 200)
            with app2.test_client() as cli:
                self.assertEqual(cli.get("/ping").status_code, 200)
                self.assertEqual(cli.get("/ping").status_code, 200)
                self.assertEqual(cli.get("/ping").status_code, 429)
                timeline.forward(1)
                self.assertEqual(cli.get("/ping").status_code, 200)
                self.assertEqual(cli.get("/slowping").status_code, 200)
                timeline.forward(59)
                self.assertEqual(cli.get("/slowping").status_code, 200)
                self.assertEqual(cli.get("/slowping").status_code, 429)
                timeline.forward(1)
                self.assertEqual(cli.get("/slowping").status_code, 200)
Example #18
0
def test_bugsnag_includes_unknown_content_type_posted_data(deliver):
    app = Flask("bugsnag")

    @app.route("/form", methods=["PUT"])
    def hello():
        raise SentinalError("oops")

    handle_exceptions(app)
    app.test_client().put("/form", data="_data", content_type="application/octet-stream")

    eq_(deliver.call_count, 1)
    payload = deliver.call_args[0][0]
    eq_(payload["events"][0]["exceptions"][0]["errorClass"], "test_flask.SentinalError")
    eq_(payload["events"][0]["metaData"]["request"]["url"], "http://localhost/form")
    ok_("_data" in payload["events"][0]["metaData"]["request"]["data"]["body"])
Example #19
0
def test_bugsnag_includes_posted_json_data(deliver):
    app = Flask("bugsnag")

    @app.route("/ajax", methods=["POST"])
    def hello():
        raise SentinalError("oops")

    handle_exceptions(app)
    app.test_client().post("/ajax", data='{"key": "value"}', content_type="application/json")

    eq_(deliver.call_count, 1)
    payload = deliver.call_args[0][0]
    eq_(payload["events"][0]["exceptions"][0]["errorClass"], "test_flask.SentinalError")
    eq_(payload["events"][0]["metaData"]["request"]["url"], "http://localhost/ajax")
    eq_(payload["events"][0]["metaData"]["request"]["data"], dict(key="value"))
Example #20
0
 def testGetUsers(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get("/users.json?_username=test&_session=1234" "&callback=blah")
         statserv.server.sessions["1234"] = ("test", request.remote_addr, True)
         statserv.server.config["adminuser"] = "admin"
         db = conn["test_db"]
         adminuser = {u"username": u"admin", u"password": "password", u"profile": ""}
         otherusers = [
             {u"username": u"other", u"password": "asdf", u"profile": u"The first other user"},
             {u"username": u"other_two", u"password": "aoeu", u"profile": u"The other other user"},
         ]
         db.stattrusers.insert(adminuser)
         db.stattrusers.insert(otherusers[0])
         db.stattrusers.insert(otherusers[1])
         statserv.server.database = conn["test_db"]
         del otherusers[0]["_id"]
         del otherusers[1]["_id"]
         del otherusers[0]["password"]
         del otherusers[1]["password"]
         expected = statserv.server.make_response("blah", {"users": otherusers})
         actual = statserv.server.get_users()
         conn.drop_database("test_db")
         self.assertEquals(
             actual,
             expected,
             "The get_users method returned something other "
             "than what we expected. Expected: `%s`, Actual: "
             "`%s`" % (expected, actual),
         )
    def setUp(self):
        app = Flask(__name__)
        self.username = "testing@example.com"
        self.password = "ShowMeTheMoney"

        def is_valid_user(username, password):
            return (username, password) == (self.username, self.password)

        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(
            ApiEndpoint(
                http_method="GET",
                endpoint="/task/basic",
                handler=get_tasks,
                authentication=BasicAuth(is_valid_user=is_valid_user),
            )
        )

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
Example #22
0
    def test_will_pass_options_to_json(self):

        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return {"foo": "bar"}

        api.add_resource(Foo1, "/foo", endpoint="bar")

        # We patch the representations module here, with two things:
        #   1. Set the settings dict() with some value
        #   2. Patch the json.dumps function in the module with a Mock object.

        from flask.ext.restful.representations import json as json_rep

        json_dumps_mock = Mock(return_value="bar")
        new_settings = {"indent": 123}

        with patch.multiple(json_rep, dumps=json_dumps_mock, settings=new_settings):
            with app.test_client() as client:
                client.get("/foo")

        # Assert that the function was called with the above settings.
        data, kwargs = json_dumps_mock.call_args
        self.assertTrue(json_dumps_mock.called)
        self.assertEqual(123, kwargs["indent"])
Example #23
0
 def test_api_delayed_initialization(self):
     app = Flask(__name__)
     api = flask_restful.Api()
     api.add_resource(HelloWorld, "/", endpoint="hello")
     api.init_app(app)
     with app.test_client() as client:
         self.assertEquals(client.get("/").status_code, 200)
Example #24
0
    def test_exception_header_forwarded(self):
        """Test that HTTPException's headers are extended properly"""
        app = Flask(__name__)
        app.config["DEBUG"] = True
        api = flask_restful.Api(app)

        class NotModified(HTTPException):
            code = 304

            def __init__(self, etag, *args, **kwargs):
                super(NotModified, self).__init__(*args, **kwargs)
                self.etag = quote_etag(etag)

            def get_headers(self, *args, **kwargs):
                """Get a list of headers."""
                return [("ETag", self.etag)]

        class Foo1(flask_restful.Resource):
            def get(self):
                flask_abort(304, etag="myETag")

        api.add_resource(Foo1, "/foo")
        flask_abort.mapping.update({304: NotModified})

        with app.test_client() as client:
            foo = client.get("/foo")
            self.assertEquals(foo.get_etag(), unquote_etag(quote_etag("myETag")))
Example #25
0
    def assertRequest(self, method, request, response, want):
        """Execute a request and check the results."""
        error = isinstance(response, Exception)
        want_status = len(want) and want[1] or 200
        want_content = self.serialize(want[0])

        app = Flask(__name__)
        app.config["TESTING"] = True
        serializer = MockSerializer(app)

        route = self.create_view(app, serializer, response)
        client_method = getattr(app.test_client(), method.lower())
        client_res = client_method(route)

        view_req, view_res = serializer.after
        self.assertEqual(client_res.status_code, want_status)
        self.assertEqual(client_res.data, want_content)
        if method == "GET":
            self.assertIsNone(view_req)
        else:
            self.assertEqual(view_req, request)
        if isinstance(response, int):
            self.assertEqual(view_res[1], response)
        else:
            if isinstance(response, Exception):
                response = get_error_response(response)
            self.assertEqual(view_res, response)
Example #26
0
def test_custom_handler():
    app = Flask(__name__)
    client = app.test_client()

    @corral.error.handle_errors(app, include_500=True)
    def handle(e):
        return e.name + "\n", e.code

    @app.route("/good")
    def good():
        return "OK"

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

    @app.route("/internal")
    def divide_by_zero():
        1 / 0

    rv = client.get("/good")
    assert rv.status_code == 200

    rv = client.get("/404")
    assert rv.data == b"Not Found\n"
    assert rv.status_code == 404

    rv = client.get("/internal")
    assert rv.data == b"Internal Server Error\n"
    assert rv.status_code == 500
Example #27
0
 def testAddUser(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         hashedpassword = hashlib.sha1("test").hexdigest()
         testRequest = c.get(
             "/user.json?_method=POST&_username=tester&"
             "_session=1234&username=test1&password=%s&"
             "fullname=tester&admin=false" % hashedpassword
         )
         db = conn.test_db
         user = {
             "username": "test1",
             "password": hashedpassword,
             "fullname": "tester",
             "admin": False,
             "profile": "",
         }
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.database = conn.test_db
         statserv.server.add_user(request)
         actual = db.stattrusers.find_one({})
         del actual["_id"]
         self.assertEquals(
             user,
             actual,
             "The add_user method did something we didn't " "expect. Expected: `%s`, actual: `%s`." % (user, actual),
         )
         conn.drop_database("test_db")
Example #28
0
    def test_non_api_error_404_catchall(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, catch_all_404s=True)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(api.default_mediatype, resp.headers["Content-Type"])
Example #29
0
 def testModUser(self):
     app = Flask(__name__)
     conn = Connection()
     with app.test_client() as c:
         testRequest = c.get(
             "/user.json?_username=tester&_session=1234&"
             "_method=PUT&username=test2&fullname=tester&"
             "admin=false&olduser=test1&profile=asdf"
         )
         user = {"username": "test1", "fullname": "tester", "admin": False, "profile": "asdf", "password": "1234"}
         db = conn.test_db
         db.stattrusers.insert(user)
         del user["_id"]
         user["username"] = "test2"
         statserv.server.sessions["1234"] = ("tester", None, True)
         statserv.server.database = conn.test_db
         statserv.server.mod_user(request)
         actual = db.stattrusers.find_one({})
         del actual["_id"]
         self.assertEquals(
             user,
             actual,
             "The mod_user method did something we didn't " "expect. Expected: `%s`, actual: `%s`." % (user, actual),
         )
         conn.drop_database("test_db")
Example #30
0
    def test_will_prettyprint_json_in_debug_mode(self):
        app = Flask(__name__)
        app.config["DEBUG"] = True
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return {"foo": "bar", "baz": "asdf"}

        api.add_resource(Foo1, "/foo", endpoint="bar")

        with app.test_client() as client:
            foo = client.get("/foo")

            # Python's dictionaries have random order (as of "new" Pythons,
            # anyway), so we can't verify the actual output here.  We just
            # assert that they're properly prettyprinted.
            lines = foo.data.splitlines()
            lines = [line.decode() for line in lines]
            self.assertEquals("{", lines[0])
            self.assertTrue(lines[1].startswith("    "))
            self.assertTrue(lines[2].startswith("    "))
            self.assertEquals("}", lines[3])

            # Assert our trailing newline.
            self.assertTrue(foo.data.endswith(b"\n"))