isso/specs/test_cors.py

66 lines
2.3 KiB
Python
Raw Normal View History

2013-11-05 12:04:48 +00:00
from __future__ import unicode_literals
try:
import unittest2 as unittest
except ImportError:
import unittest
2013-11-05 12:04:48 +00:00
from werkzeug.test import Client
from werkzeug.wrappers import Response
from isso.wsgi import CORSMiddleware
from isso.utils import origin
2013-11-05 12:04:48 +00:00
def hello_world(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return ["Hello, World."]
class CORSTest(unittest.TestCase):
def test_simple(self):
2013-11-05 12:04:48 +00:00
app = CORSMiddleware(hello_world,
origin=origin([
"https://example.tld/",
"http://example.tld/",
"http://example.tld",
]),
allowed=("Foo", "Bar"), exposed=("Spam", ))
2013-11-05 12:04:48 +00:00
client = Client(app, Response)
2013-11-05 12:04:48 +00:00
rv = client.get("/", headers={"ORIGIN": "https://example.tld"})
2013-11-05 12:04:48 +00:00
self.assertEqual(rv.headers["Access-Control-Allow-Origin"], "https://example.tld")
self.assertEqual(rv.headers["Access-Control-Allow-Credentials"], "true")
self.assertEqual(rv.headers["Access-Control-Allow-Methods"], "HEAD, GET, POST, PUT, DELETE")
self.assertEqual(rv.headers["Access-Control-Allow-Headers"], "Foo, Bar")
self.assertEqual(rv.headers["Access-Control-Expose-Headers"], "Spam")
2013-11-05 12:04:48 +00:00
a = client.get("/", headers={"ORIGIN": "http://example.tld"})
self.assertEqual(a.headers["Access-Control-Allow-Origin"], "http://example.tld")
2013-11-05 12:04:48 +00:00
b = client.get("/", headers={"ORIGIN": "http://example.tld"})
self.assertEqual(b.headers["Access-Control-Allow-Origin"], "http://example.tld")
2013-11-05 12:04:48 +00:00
c = client.get("/", headers={"ORIGIN": "http://foo.other"})
self.assertEqual(c.headers["Access-Control-Allow-Origin"], "https://example.tld")
2013-11-05 12:04:48 +00:00
def test_preflight(self):
2013-11-05 12:04:48 +00:00
app = CORSMiddleware(hello_world, origin=origin(["http://example.tld"]),
allowed=("Foo", ), exposed=("Bar", ))
client = Client(app, Response)
2013-11-05 12:04:48 +00:00
rv = client.open(method="OPTIONS", path="/", headers={"ORIGIN": "http://example.tld"})
self.assertEqual(rv.status_code, 200)
2013-11-05 12:04:48 +00:00
for hdr in ("Origin", "Headers", "Credentials", "Methods"):
self.assertIn("Access-Control-Allow-%s" % hdr, rv.headers)
2013-11-05 12:04:48 +00:00
self.assertEqual(rv.headers["Access-Control-Allow-Origin"], "http://example.tld")