1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
import unittest
from flask import Flask
import flask_restful
from flask_restful.utils import cors
class CORSTestCase(unittest.TestCase):
def test_crossdomain(self):
class Foo(flask_restful.Resource):
@cors.crossdomain(origin='*')
def get(self):
return "data"
app = Flask(__name__)
api = flask_restful.Api(app)
api.add_resource(Foo, '/')
with app.test_client() as client:
res = client.get('/')
self.assertEqual(res.status_code, 200)
self.assertEqual(res.headers['Access-Control-Allow-Origin'], '*')
self.assertEqual(res.headers['Access-Control-Max-Age'], '21600')
self.assertTrue('HEAD' in res.headers['Access-Control-Allow-Methods'])
self.assertTrue('OPTIONS' in res.headers['Access-Control-Allow-Methods'])
self.assertTrue('GET' in res.headers['Access-Control-Allow-Methods'])
def test_access_control_expose_headers(self):
class Foo(flask_restful.Resource):
@cors.crossdomain(origin='*',
expose_headers=['X-My-Header', 'X-Another-Header'])
def get(self):
return "data"
app = Flask(__name__)
api = flask_restful.Api(app)
api.add_resource(Foo, '/')
with app.test_client() as client:
res = client.get('/')
self.assertEqual(res.status_code, 200)
self.assertTrue('X-MY-HEADER' in res.headers['Access-Control-Expose-Headers'])
self.assertTrue('X-ANOTHER-HEADER' in res.headers['Access-Control-Expose-Headers'])
def test_access_control_allow_methods(self):
class Foo(flask_restful.Resource):
@cors.crossdomain(origin='*',
methods={"HEAD","OPTIONS","GET"})
def get(self):
return "data"
def post(self):
return "data"
app = Flask(__name__)
api = flask_restful.Api(app)
api.add_resource(Foo, '/')
with app.test_client() as client:
res = client.get('/')
self.assertEqual(res.status_code, 200)
self.assertTrue('HEAD' in res.headers['Access-Control-Allow-Methods'])
self.assertTrue('OPTIONS' in res.headers['Access-Control-Allow-Methods'])
self.assertTrue('GET' in res.headers['Access-Control-Allow-Methods'])
self.assertTrue('POST' not in res.headers['Access-Control-Allow-Methods'])
def test_no_crossdomain(self):
class Foo(flask_restful.Resource):
def get(self):
return "data"
app = Flask(__name__)
api = flask_restful.Api(app)
api.add_resource(Foo, '/')
with app.test_client() as client:
res = client.get('/')
self.assertEqual(res.status_code, 200)
self.assertTrue('Access-Control-Allow-Origin' not in res.headers)
self.assertTrue('Access-Control-Allow-Methods' not in res.headers)
self.assertTrue('Access-Control-Max-Age' not in res.headers)
|