Skip to content
This repository was archived by the owner on Aug 16, 2022. It is now read-only.

Commit 47afa66

Browse files
committed
fixed #38
1 parent 971d71d commit 47afa66

File tree

13 files changed

+297
-189
lines changed

13 files changed

+297
-189
lines changed

tests/berlinium/asleep_client.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
#!/usr/bin/env python
2+
3+
import sys
24
import time
35
import logging
6+
47
import websocket
5-
import json
8+
9+
import ujson as json
610

711
import set_path
812
from tilde.core.settings import settings
913

10-
logging.basicConfig(level=logging.DEBUG)
14+
15+
logging.basicConfig(level=logging.INFO)
1116
START_TIME = time.time()
1217

1318
class RespHandler(object):
@@ -27,10 +32,12 @@ def on_message(self, ws, message):
2732
else:
2833
logging.info("Client done in: %1.2f sc" % (time.time() - START_TIME))
2934
ws.close()
35+
sys.exit(0)
3036

3137
@classmethod
3238
def on_error(self, ws, error):
3339
logging.debug(error)
40+
sys.exit(1)
3441

3542
@classmethod
3643
def on_close(self, ws):

tests/berlinium/asleep_server.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env python
2-
import json
2+
33
import time
44
import logging
55

@@ -9,30 +9,29 @@
99
from sockjs.tornado import SockJSRouter
1010

1111
import set_path
12-
from tilde.core.settings import settings, connect_database
12+
from tilde.core.settings import settings
1313
from tilde.core.api import API
14-
from tilde.berlinium.block_impl import Connection
14+
from tilde.berlinium import Async_Connection
1515

1616

17-
Tilde = API()
17+
logging.basicConfig(level=logging.INFO)
1818

19+
Tilde = API()
1920
settings['debug_regime'] = False
20-
logging.basicConfig(level=logging.DEBUG)
2121

2222
class SleepTester:
2323
@staticmethod
24-
def login(req, session_id):
25-
Connection.Clients[session_id].authorized = True
26-
Connection.Clients[session_id].db = connect_database(settings, default_actions=False, scoped=True)
24+
def login(req, client_id, db_session):
25+
Connection.Clients[client_id].authorized = True
2726
return "OK", None
2827

2928
@staticmethod
30-
def sleep(req, session_id):
29+
def sleep(req, client_id, db_session):
3130
result, error = '', None
3231
try: req = float(req)
3332
except: return result, 'Not a number!'
3433

35-
current_engine = Connection.Clients[session_id].db.get_bind()
34+
current_engine = db_session.get_bind()
3635

3736
if settings['db']['engine'] == 'postgresql':
3837
current_engine.execute(text('SELECT pg_sleep(:i)'), **{'i': req})
@@ -43,16 +42,18 @@ def sleep(req, session_id):
4342
c = conn.cursor()
4443
c.execute('SELECT sq_sleep(%s)' % req)
4544

46-
result = Tilde.count(Connection.Clients[session_id].db)
45+
result = Tilde.count(db_session)
4746
return result, error
4847

4948
if __name__ == "__main__":
49+
Connection = Async_Connection
5050
Connection.GUIProvider = SleepTester
5151
DuplexRouter = SockJSRouter(Connection)
5252
application = web.Application(DuplexRouter.urls, debug=False)
5353
application.listen(settings['webport'], address='0.0.0.0')
5454

55-
logging.debug("Server started")
55+
logging.info("DB is %s" % settings['db']['engine'])
56+
logging.info("Connections are %s" % Connection.Type)
57+
logging.info("Server started")
5658

57-
try: ioloop.IOLoop.instance().start()
58-
except KeyboardInterrupt: pass
59+
ioloop.IOLoop.instance().start()

tests/berlinium/asleep_test.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,25 @@
11
#!/usr/bin/env python
2+
23
import os, sys
34
import time
45
import subprocess
56

6-
77
if __name__ == "__main__":
8-
bd = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
9-
dmn = subprocess.Popen([sys.executable, os.path.join(bd, 'asleep_server.py')], env=os.environ.copy())
8+
try:
9+
prcnum = int(sys.argv[1])
10+
except (IndexError, ValueError):
11+
sys.exit("Usage: script #processes")
12+
13+
basedir = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
14+
daemon = subprocess.Popen([sys.executable, os.path.join(basedir, 'asleep_server.py')])
1015
time.sleep(2) # wait for initialization
1116

12-
for i in range(5):
13-
subprocess.Popen([sys.executable, os.path.join(bd, 'asleep_client.py')], env=os.environ.copy())
14-
time.sleep(0.5)
17+
children = []
18+
for i in range(prcnum):
19+
children.append( subprocess.Popen([sys.executable, os.path.join(basedir, 'asleep_client.py')]) )
20+
21+
time.sleep(prcnum + 2)
22+
daemon.terminate()
1523

16-
time.sleep(7)
17-
dmn.terminate()
24+
for i in children:
25+
assert i.poll() == 0

tests/berlinium/basic_client.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
#!/usr/bin/env python
2+
3+
import sys
24
import time
35
import logging
6+
47
import bcrypt
58
import websocket
69

@@ -11,49 +14,45 @@
1114
from tilde.core.settings import settings
1215

1316

14-
logging.basicConfig(level=logging.DEBUG)
17+
logging.basicConfig(level=logging.INFO)
1518

1619
START_TIME = time.time()
1720

1821
USER, PASS = 'test', 'test'
1922

2023
class RespHandler(object):
24+
@classmethod
25+
def on_error(self, ws, error):
26+
logging.error(error)
27+
sys.exit(1)
28+
29+
@classmethod
30+
def on_close(self, ws):
31+
logging.debug("Closed")
32+
ws.close()
33+
2134
@classmethod
2235
def on_open(self, ws):
2336
logging.debug("Opened")
2437
pwhash = bcrypt.hashpw(PASS, bcrypt.gensalt())
25-
to_send = {'act': 'login', 'req': {'user': USER, 'pass': pwhash}}
26-
ws.send(json.dumps(to_send))
38+
ws.send(json.dumps({'act': 'login', 'req': {'user': USER, 'pass': pwhash}}))
2739

2840
@classmethod
2941
def on_message(self, ws, message):
30-
logging.info("Received: %s" % message[:100])
42+
logging.debug("Received: %s" % message[:100])
3143
message = json.loads(message)
3244

3345
if message['act'] == 'login':
3446
if message['result'] == 'OK':
35-
to_send = {'act': 'tags', 'req': {'tids':0}}
36-
ws.send(json.dumps(to_send))
47+
ws.send(json.dumps({'act': 'sleep', 'req': 3}))
3748
else:
38-
logging.info("Auth failed!")
39-
40-
elif message['act'] == 'tags':
41-
logging.info(message['result'])
42-
to_send = {'act': 'sleep', 'req': 4}
43-
ws.send(json.dumps(to_send))
49+
logging.error("Auth failed!")
50+
sys.exit(1)
4451

4552
elif message['act'] == 'sleep':
46-
logging.info("Client done in: %1.2f sc" % (time.time() - START_TIME))
53+
logging.info("Client done in %1.2f sc" % (time.time() - START_TIME))
4754
ws.close()
48-
49-
@classmethod
50-
def on_error(self, ws, error):
51-
logging.error(error)
52-
53-
@classmethod
54-
def on_close(self, ws):
55-
logging.debug("Closed")
56-
ws.close()
55+
sys.exit(0)
5756

5857

5958
if __name__ == "__main__":
@@ -63,4 +62,5 @@ def on_close(self, ws):
6362
on_message = RespHandler.on_message,
6463
on_error = RespHandler.on_error,
6564
on_close = RespHandler.on_close)
65+
logging.debug("Started")
6666
ws.run_forever()

tests/berlinium/basic_server.py

Lines changed: 12 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
23
import time
34
import logging
45

@@ -8,10 +9,10 @@
89
from sockjs.tornado import SockJSRouter
910

1011
import set_path
11-
from tilde.core.settings import settings, connect_database
12+
from tilde.core.settings import settings
1213
from tilde.core.api import API
1314
import tilde.core.model as model
14-
from tilde.berlinium import Connection, add_redirection
15+
from tilde.berlinium import Async_Connection, add_redirection
1516

1617

1718
logging.basicConfig(level=logging.INFO)
@@ -22,7 +23,7 @@
2223

2324
class TildeGUIProvider:
2425
@staticmethod
25-
def login(req, session_id):
26+
def login(req, client_id, db_session):
2627
result, error = None, None
2728
if not isinstance(req, dict): return result, 'Invalid request!'
2829

@@ -36,59 +37,25 @@ def login(req, session_id):
3637

3738
if user != USER or not pass_match:
3839
return result, 'Unauthorized!'
39-
Connection.Clients[session_id].authorized = True
40-
Connection.Clients[session_id].db = connect_database(settings, default_actions=False, scoped=True)
41-
return "OK", None
42-
43-
@staticmethod
44-
def tags(req, session_id):
45-
result, error = [], None
46-
if not isinstance(req, dict): return result, 'Invalid request!'
47-
48-
if not 'tids' in req: tids = None # NB json may contain nulls
49-
else: tids = req['tids']
50-
51-
if not tids:
52-
for tid, cid, topic in Connection.Clients[session_id].db.query(model.uiTopic.tid, model.uiTopic.cid, model.uiTopic.topic).all():
53-
# TODO assure there are checksums for every tid
54-
try: match = [x for x in Tilde.hierarchy if x['cid'] == cid][0]
55-
except IndexError: return None, 'Schema and data do not match: different versions of code and database?'
56-
57-
if not match.get('has_facet'): continue
58-
59-
sort = 1000 if not 'sort' in match else match['sort']
40+
Connection.Clients[client_id].authorized = True
6041

61-
ready_topic = {'tid': tid, 'topic': topic, 'sort': 0}
62-
63-
for n, tag in enumerate(result):
64-
if tag['category'] == match['category']:
65-
result[n]['content'].append( ready_topic )
66-
break
67-
else: result.append({'cid': match['cid'], 'category': match['category'], 'sort': sort, 'content': [ ready_topic ]})
68-
69-
result.sort(key=lambda x: x['sort'])
70-
result = {'blocks': result, 'cats': Tilde.supercategories}
71-
72-
return result, error
42+
return "OK", None
7343

7444
@staticmethod
75-
def sleep(req, session_id):
45+
def sleep(req, client_id, db_session):
7646
result, error = '', None
7747
try: req = float(req)
7848
except: return result, 'Not a number!'
7949

8050
time.sleep(req)
8151

82-
result = Tilde.count(Connection.Clients[session_id].db)
52+
result = Tilde.count(db_session)
8353

8454
return result, error
8555

86-
@staticmethod
87-
def example(req, session_id):
88-
result, error = '', None
89-
return result, error
9056

9157
if __name__ == "__main__":
58+
Connection = Async_Connection # test with: select * from pg_stat_activity;
9259
Connection.GUIProvider = TildeGUIProvider
9360
DuplexRouter = SockJSRouter(Connection)
9461

@@ -98,7 +65,9 @@ def example(req, session_id):
9865
)
9966
application.listen(settings['webport'], address='0.0.0.0')
10067

101-
logging.debug("Server started")
68+
logging.info("DB is %s" % settings['db']['engine'])
69+
logging.info("Connections are %s" % Connection.Type)
70+
logging.info("Server started")
10271

10372
try: ioloop.IOLoop.instance().start()
10473
except KeyboardInterrupt: pass

tests/berlinium/basic_test.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,25 @@
11
#!/usr/bin/env python
2+
23
import os, sys
34
import time
45
import subprocess
56

6-
77
if __name__ == "__main__":
8-
bd = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
9-
dmn = subprocess.Popen([sys.executable, os.path.join(bd, 'basic_server.py')], env=os.environ.copy())
8+
try:
9+
prcnum = int(sys.argv[1])
10+
except (IndexError, ValueError):
11+
sys.exit("Usage: script #processes")
12+
13+
basedir = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
14+
daemon = subprocess.Popen([sys.executable, os.path.join(basedir, 'basic_server.py')])
1015
time.sleep(2) # wait for initialization
1116

12-
for i in range(5):
13-
subprocess.Popen([sys.executable, os.path.join(bd, 'basic_client.py')], env=os.environ.copy())
14-
time.sleep(0.5)
17+
children = []
18+
for i in range(prcnum):
19+
children.append( subprocess.Popen([sys.executable, os.path.join(basedir, 'basic_client.py')]) )
20+
21+
time.sleep(prcnum + 2)
22+
daemon.terminate()
1523

16-
time.sleep(7)
17-
dmn.terminate()
24+
for i in children:
25+
assert i.poll() == 0

0 commit comments

Comments
 (0)