Skip to content

Commit

Permalink
Improve mock server, test log out routine
Browse files Browse the repository at this point in the history
  • Loading branch information
nielstron committed Jun 8, 2020
1 parent 7afbf5c commit ad32fd2
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 22 deletions.
4 changes: 2 additions & 2 deletions pyblnet/blnet_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,9 @@ def set_digital_value(self, digital_id, value):
else:
raise ValueError("Illegal input string {}".format(value))
elif isinstance(value, int) and not isinstance(value, bool):
if value is 3 or value is 2 or value is 1:
if value in (1, 2, 3):
value = str(value)
elif value is 0:
elif value == 0:
value = '1'
else:
raise ValueError("Illegal input integer {}".format(value))
Expand Down
42 changes: 33 additions & 9 deletions pyblnet/tests/test_structure/blnet_mock_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,20 @@
from pathlib import Path

SERVER_DIR = Path(__file__).parent or Path('.')
PASSWORD = '0123'

COOKIE_RANGE = (0xAAAA, 0xFFFF)
COOKIE_NUM = COOKIE_RANGE[1] - COOKIE_RANGE[0]
LOGIN_COOKIES = [hex(i) for i in range(*COOKIE_RANGE)]


class BLNETServer(HTTPServer):

current_log_in_cookie = 0

# Currently allowed login cookie
# or none if no one logged in
logged_in = True
logged_in = None
# no login necessary
password = None
# access to digital nodes
Expand All @@ -30,8 +37,18 @@ def set_password(self, password):
self.password = password
self.logged_in = None

def set_logged_in(self, cookie):
self.logged_in = cookie
def log_in(self):
if self.logged_in is not None:
return False
self.logged_in = LOGIN_COOKIES[self.current_log_in_cookie]
self.current_log_in_cookie = (self.current_log_in_cookie + 1) % COOKIE_NUM
return self.logged_in

def log_out(self):
self.logged_in = None

def is_logged_in(self, cookie):
return cookie is not None and self.logged_in == cookie

def set_node(self, id, value):
self.nodes[id] = value
Expand All @@ -48,6 +65,8 @@ def unset_blocked(self):

class BLNETRequestHandler(SimpleHTTPRequestHandler):

server: BLNETServer

def do_GET(self):
"""
Handle get request, but check for errors in protocol
Expand All @@ -57,11 +76,14 @@ def do_GET(self):
self.send_error(403, "Access denied because server is blocked")
return
path = self.translate_path(self.path)
if (self.server.is_logged_in(self.headers.get("cookie"))
and "?blL=1" in self.requestline):
self.server.log_out()
# Only access that is allowed without login is main.html
if (not Path(path) == SERVER_DIR
and not Path(path) == SERVER_DIR.joinpath('main.htm')
and not Path(path) == SERVER_DIR.joinpath('main.html')):
if not self.server.logged_in:
if not self.server.is_logged_in(self.headers.get("cookie")):
self.send_error(403, "Not logged in, access denied")
return
# Parse node sets
Expand Down Expand Up @@ -121,8 +143,11 @@ def do_POST(self):
return
# All checks passed? set Set-Cookie header and do_GET
# random cookie - do not hardcode
self.server.set_logged_in('C1A3')
self.headers.add_header('Cookie', 'C1A3')
cookie = self.server.log_in()
if not cookie:
self.send_error(403, "Previous user did not log out")
return
self.headers.add_header('Cookie', cookie)
self.do_GET()

def translate_path(self, path):
Expand Down Expand Up @@ -203,9 +228,8 @@ def send_head(self):
self.send_header("Last-Modified",
self.date_time_string(fs.st_mtime))
# Addition: send cookie
if (self.server.logged_in is not None
and self.server.logged_in == self.headers.get('Cookie')):
self.send_header('Set-Cookie', 'C1A3')
if self.server.is_logged_in(self.headers.get('Cookie')):
self.send_header('Set-Cookie', self.server.logged_in)
self.end_headers()
return f
except:
Expand Down
31 changes: 20 additions & 11 deletions pyblnet/tests/test_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# general requirements
import unittest
from .test_structure.server_control import Server
from .test_structure.blnet_mock_server import BLNETServer, BLNETRequestHandler
from .test_structure.blnet_mock_server import BLNETServer, BLNETRequestHandler, PASSWORD

# For the server in this case
import time
Expand All @@ -14,7 +14,6 @@
from .web_raw.web_state import STATE, STATE_ANALOG, STATE_DIGITAL

ADDRESS = 'localhost'
PASSWORD = '0123'


class OfflineTest(unittest.TestCase):
Expand All @@ -27,7 +26,7 @@ def test_blnet(self):

def test_blnet_web(self):
try:
blnet = BLNETWeb(self.url)
BLNETWeb(self.url)
self.fail("Didn't throw an exception for offline blnetweb")
except ValueError:
pass
Expand Down Expand Up @@ -71,16 +70,18 @@ def test_blnet(self):
self.server.set_blocked()
self.assertTrue(test_blnet(self.url, timeout=10))

def test_blnet_login(self):
""" Test logging in """
self.assertTrue(
BLNETWeb(self.url, password=PASSWORD, timeout=10).log_in())
def test_blnet_web_log_in(self):
"""
Test logging in via different urls
and that log out after a with clause happens correctly
"""
with BLNETWeb(self.url, password=PASSWORD, timeout=10) as blnet:
self.assertTrue(blnet.logged_in())
# test without http
self.assertTrue(
BLNETWeb(
"{}:{}".format(ADDRESS, self.port),
with BLNETWeb("{}:{}".format(ADDRESS, self.port),
password=PASSWORD,
timeout=10).log_in())
timeout=10) as blnet:
self.assertTrue(blnet.logged_in())

def test_blnet_fetch(self):
""" Test fetching data in higher level class """
Expand Down Expand Up @@ -186,6 +187,14 @@ def test_blnet_web_set_digital(self):
except ValueError:
pass

def test_blnet_web_log_out(self):
""" Test setting digital values """
blnet = BLNETWeb(self.url, password=PASSWORD, timeout=10)
self.assertFalse(blnet.logged_in())
with blnet as blnet:
self.assertTrue(blnet.logged_in())
self.assertFalse(blnet.logged_in())

def tearDown(self):
self.server_control.stop_server()
pass
Expand Down

0 comments on commit ad32fd2

Please sign in to comment.