Skip to content

Commit

Permalink
fix(server): ensure complete http header is present
Browse files Browse the repository at this point in the history
  • Loading branch information
ssube committed Dec 26, 2019
1 parent ad58e32 commit efa6694
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
3 changes: 3 additions & 0 deletions prometheus_express/server.py
Expand Up @@ -77,6 +77,9 @@ def parse_headers(self, req):
lines = req.split(http_break)
start = lines[0].split(' ')

if len(start) < 3:
raise ValueError('request does not have all HTTP components')

return ({
'method': start[0],
'path': start[1],
Expand Down
67 changes: 67 additions & 0 deletions tests/test_server.py
@@ -0,0 +1,67 @@
import unittest
import prometheus_express.router as pr
import prometheus_express.server as ps

class MockConnection(object):
def __init__(self, body):
self.accum = []
self.body = body
self.buffer = []
self.index = 0
self.open = True

def recv(self, n):
print('recv', n)
self.buffer = self.body[self.index : self.index + n]
self.index += n
return self.buffer

def send(self, chunk):
self.accum.append(chunk)

def close(self):
self.open = False

def response(self):
return ''.join(self.accum)

class MockSocket(object):
def __init__(self, addr, body):
self.addr = addr
self.body = body
self.conn = MockConnection(self.body)

def accept(self):
return (self.conn, self.addr)

class ServerAcceptTest(unittest.TestCase):
def test_valid(self):
body = 'test body'
mock = MockSocket('0.0.0.1', 'GET / HTTP/1.1\r\n{}'.format(body))

s = ps.Server(mock)
r = pr.Router([
('GET', '/', lambda headers, requestBody: {
'content': body,
'status': 200,
}),
])
s.accept(r)

result = mock.conn.response()
self.assertEqual(
result.split('\r\n')[-1],
body
)

def test_missing_verb(self):
body = 'test body'
mock = MockSocket('0.0.0.1', 'HTTP/1.1\r\n{}'.format(body))

s = ps.Server(mock)
r = pr.Router([
('GET', '/', lambda: body),
])

with self.assertRaises(ValueError):
s.accept(r)

0 comments on commit efa6694

Please sign in to comment.