def test_start_committee(self): peer_api_one = api.create_app() peer_api_one.config['TESTING'] = True peer_api_one.config['DEBUG'] = False peer_api_two = api.create_app() peer_api_two.config['TESTING'] = True peer_api_two.config['DEBUG'] = False peer_api_three = api.create_app() peer_api_three.config['TESTING'] = True peer_api_three.config['DEBUG'] = False peer_api_four = api.create_app() peer_api_four.config['TESTING'] = True peer_api_four.config['DEBUG'] = False peers = [peer_api_one.test_client(), peer_api_two.test_client(), peer_api_three.test_client(), peer_api_four.test_client()] peers[0].get('/start/a/b') peers[1].get('/start/a/c') peers[2].get('/start/a/d') peers[3].get('/start/a/e') docker = docker_api.from_env() self.assertEqual(8, len(docker.containers.list())) val_keys = [get_plain_text(p.get('/val+key/a')) for p in peers] usr_keys = [get_plain_text(p.get('/user+key/a')) for p in peers] genesis_json = json.loads(json.dumps({ USER_KEY: usr_keys, VALIDATOR_KEY: val_keys })) peers[0].post('/make+genesis/a', json=genesis_json) join_request_data = {NEIGHBOURS: []} ip = 1 quorum = 'b' for p in peers: # use pretend API address and ports because app is not actually running join_request_data[NEIGHBOURS].append( {API_IP: "192.168.1.{}".format(ip), DOCKER_IP: get_plain_text(p.get('/ip/a')), PORT: "5000", QUORUM_ID: quorum}) ip += 1 quorum = chr(ord(quorum) + 1) data = json.loads(json.dumps(join_request_data)) for p in peers: p.post('/join/a', json=data) peers[0].post('/submit/', json=TRANSACTION_A_JSON) time.sleep(3) for p in peers: self.assertEqual('999', get_plain_text(p.post('/get/', json=TRANSACTION_A_JSON)))
def test_make_genesis(self): peer_api_one = api.create_app() peer_api_one.config['TESTING'] = True peer_api_one.config['DEBUG'] = False peer_api_two = api.create_app() peer_api_two.config['TESTING'] = True peer_api_two.config['DEBUG'] = False peer_api_three = api.create_app() peer_api_three.config['TESTING'] = True peer_api_three.config['DEBUG'] = False peer_api_four = api.create_app() peer_api_four.config['TESTING'] = True peer_api_four.config['DEBUG'] = False peers = [ peer_api_one.test_client(), peer_api_two.test_client(), peer_api_three.test_client(), peer_api_four.test_client() ] peers[0].get('/start/a/b') peers[1].get('/start/a/c') peers[2].get('/start/a/d') peers[3].get('/start/a/e') docker = docker_api.from_env() self.assertEqual(8, len(docker.containers.list())) val_keys = [get_plain_text(p.get('/val+key/a')) for p in peers] usr_keys = [get_plain_text(p.get('/user+key/a')) for p in peers] genesis_json = json.loads( json.dumps({ USER_KEY: usr_keys, VALIDATOR_KEY: val_keys })) peers[0].post('/make+genesis/a', json=genesis_json) pbft_settings = docker.containers.list()[-1].exec_run( "ls pbft-settings.batch").output.decode('utf-8').strip() config_consensus = docker.containers.list()[-1].exec_run( "ls config-consensus.batch").output.decode('utf-8').strip() config_genesis = docker.containers.list()[-1].exec_run( "ls config-genesis.batch").output.decode('utf-8').strip() self.assertEqual('pbft-settings.batch', pbft_settings) self.assertEqual('config-consensus.batch', config_consensus) self.assertEqual('config-genesis.batch', config_genesis)
def test_add(self): app = api.create_app() app.config['TESTING'] = True app.config['DEBUG'] = False client = app.test_client() client.get('/start/a/b') response = client.post('/add/a', json=ADD_A_JSON) self.assertEqual(200, response.status_code) self.assertEqual([ { API_IP: "192.168.1.200", PORT: "5000", QUORUM_ID: "c" }, { API_IP: "192.168.1.300", PORT: "5000", QUORUM_ID: "d" }, { API_IP: "192.168.1.400", PORT: "5000", QUORUM_ID: "e" } ], app.config[QUORUMS]["a"]) self.assertEqual(app.config[QUORUMS]["b"], [])
def test_min_intersection_2_less_than_rest_depth_0(self, mock_get): # Almost fully connected, missing A-C peer and B-D peer intersection_maps = [ {'a': {'b': {"localhost": 0}, 'c': {}, 'd': {"192.168.1.300:5000": 0}, 'e': {"192.168.1.400:5000": 0}}, 'b': {'c': {}, 'd': {}, 'e': {}}, 'c': {'d': {"192.168.1.800:5000": 0}, 'e': {}}, 'd': {'e': {"192.168.1.1000:5000": 0}}}, {'a': {'b': {"localhost": 0}, 'c': {}, 'd': {"192.168.1.300:5000": 0}, 'e': {"192.168.1.400:5000": 0}}, 'b': {'c': {}, 'd': {}, 'e': {"192.168.1.700:5000": 0}}, 'c': {'d': {}, 'e': {"192.168.1.900:5000": 0}}, 'd': {'e': {"192.168.1.1000:5000": 0}}}, {'a': {'b': {"localhost": 0}, 'c': {}, 'd': {}, 'e': {}}, 'b': {'c': {"192.168.1.500:5000": 0}, 'd': {}, 'e': {"192.168.1.700:5000": 0}}, 'c': {'d': {"192.168.1.800:5000": 0}, 'e': {"192.168.1.900:5000": 0}}, 'd': {'e': {}}}, {'a': {'b': {"localhost": 0}, 'c': {}, 'd': {}, 'e': {"192.168.1.400:5000": 0}}, 'b': {'c': {"192.168.1.500:5000": 0}, 'd': {}, 'e': {"192.168.1.700:5000": 0}}, 'c': {'d': {}, 'e': {"192.168.1.900:5000": 0}}, 'd': {'e': {"192.168.1.1000:5000": 0}}} ] side_effects = [] for intersection_map in intersection_maps: res = Mock(spec=Response) res.text = json.dumps(intersection_map) res.status_code = 200 side_effects.append(res) mock_get.side_effect = side_effects app = api.create_app() app.config['TESTING'] = True app.config['DEBUG'] = False test_client = app.test_client() test_client.get('/start/a/b') test_client.post('/add/a', json=ADD_A_JSON_MISSING_A_C) test_client.post('/add/b', json=ADD_B_JSON_MISSING_B_D) time.sleep(1) res = test_client.get('/min+intersection') self.assertEqual(res.get_json(), ['a', 'c'])
def create_app(self): self.temp_dir = tempfile.mkdtemp(suffix='-bot-lax-api-test') cxx = api.create_app({ 'DEBUG': True, 'UPLOAD_FOLDER': self.temp_dir }) return cxx.app
def db_testing(): os.environ["DATABASE_URL"] = "sqlite:///test.db" app = create_app("testing") with app.app_context(): db.create_all() yield app db.drop_all()
def test_api_start(self): app = api.create_app() app.config['TESTING'] = True app.config['DEBUG'] = False client = app.test_client() # test that wrong url do nothing response = client.get('/start/') self.assertEqual(404, response.status_code) self.assertIsNone(app.config[PBFT_INSTANCES]) self.assertEqual({}, app.config[QUORUMS]) response = client.get('/start/a/') self.assertEqual(404, response.status_code) self.assertIsNone(app.config[PBFT_INSTANCES]) self.assertEqual({}, app.config[QUORUMS]) # test actual url works response = client.get('/start/a/b') self.assertEqual(200, response.status_code) self.assertIsNotNone(app.config[PBFT_INSTANCES]) self.assertEqual({'a': [], 'b': []}, app.config[QUORUMS]) docker = docker_api.from_env() self.assertEqual(2, len(docker.containers.list())) # get info on container a container_ip = docker.containers.list()[1].exec_run( "hostname -i").output.decode('utf-8').strip() container_val_key = docker.containers.list()[1].exec_run("cat {val_pub}".format(val_pub=VKEY["pub"])) \ .output.decode('utf-8').strip() container_user_key = docker.containers.list()[1].exec_run("cat {user_pub}".format(user_pub=UKEY["pub"])) \ .output.decode('utf-8').strip() self.assertEqual(get_plain_text(client.get('/ip/a')), container_ip) self.assertEqual(get_plain_text(client.get('/val+key/a')), container_val_key) self.assertEqual(get_plain_text(client.get('/user+key/a')), container_user_key) self.assertNotEqual(get_plain_text(client.get('/val+key/a')), get_plain_text(client.get('/user+key/a'))) # get info on container b container_ip = docker.containers.list()[0].exec_run( "hostname -i").output.decode('utf-8').strip() container_val_key = docker.containers.list()[0].exec_run("cat {val_pub}".format(val_pub=VKEY["pub"])) \ .output.decode('utf-8').strip() container_user_key = docker.containers.list()[0].exec_run("cat {user_pub}".format(user_pub=UKEY["pub"])) \ .output.decode('utf-8').strip() self.assertEqual(get_plain_text(client.get('/ip/b')), container_ip) self.assertEqual(get_plain_text(client.get('/val+key/b')), container_val_key) self.assertEqual(get_plain_text(client.get('/user+key/b')), container_user_key) self.assertNotEqual(get_plain_text(client.get('/val+key/b')), get_plain_text(client.get('/user+key/b')))
def test_request_join(self, mock_post): side_effects = [ ['a', 'b'], ROUTE_EXECUTED_CORRECTLY, ROUTE_EXECUTED_CORRECTLY ] mock_post.side_effect = side_effects app = api.create_app() app.config['TESTING'] = True app.config['DEBUG'] = False test_client = app.test_client() time.sleep(1) res = test_client.post('/request+join', json={API_IP: "192.168.0.0", PORT: 5000})
def test_forwarding(self, mock_post): # making test app and setting up test envi app = create_app() app.config['TESTING'] = True app.config['DEBUG'] = False app.config[QUORUMS]["a"] = [{API_IP: "192.168.1.200", PORT: "5000", QUORUM_ID: "c"}, {API_IP: "192.168.1.300", PORT: "5000", QUORUM_ID: "d"}, {API_IP: "192.168.1.400", PORT: "5000", QUORUM_ID: "e"}] mock_post.return_value = '<Response [200]>' forward(app, 'submit/', 'c', TRANSACTION_C_JSON) self.assertEqual(2, len(mock_post.call_args)) self.assertEqual('http://192.168.1.200:5000/submit/', mock_post.call_args[0][0]) self.assertEqual(TRANSACTION_C_JSON, mock_post.call_args[1]['json'])
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client setup_db(self.app) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all()
def start(self): if self.port is None: smart_shard_peer_log.error('start called with no PORT') if self.app is not None: smart_shard_peer_log.error('app on {} is already running'.format(self.port)) self.app = mp.Process() self.app.api = create_app(self.inter) temp = self.app.api self.app = mp.Process(target=self.app.api.run, kwargs=({'port': self.port})) self.app.api = temp self.app.daemon = True # run the api as daemon so it terminates with the peer process process self.app.start()
def test_start_with_peer(self): a = SawtoothContainer() b = SawtoothContainer() id_a = 'a' id_b = 'b' p = Intersection(a, b, id_a, id_b) app = api.create_app(p) app.config['TESTING'] = True app.config['DEBUG'] = False client = app.test_client() docker = docker_api.from_env() # get info on container a container_ip = docker.containers.list()[1].exec_run( "hostname -i").output.decode('utf-8').strip() container_val_key = docker.containers.list()[1].exec_run("cat {val_pub}".format(val_pub=VKEY["pub"])) \ .output.decode('utf-8').strip() container_user_key = docker.containers.list()[1].exec_run("cat {user_pub}".format(user_pub=UKEY["pub"])) \ .output.decode('utf-8').strip() self.assertEqual(get_plain_text(client.get('/ip/a')), container_ip) self.assertEqual(get_plain_text(client.get('/val+key/a')), container_val_key) self.assertEqual(get_plain_text(client.get('/user+key/a')), container_user_key) self.assertNotEqual(get_plain_text(client.get('/val+key/a')), get_plain_text(client.get('/user+key/a'))) # get info on container b container_ip = docker.containers.list()[0].exec_run( "hostname -i").output.decode('utf-8').strip() container_val_key = docker.containers.list()[0].exec_run("cat {val_pub}".format(val_pub=VKEY["pub"])) \ .output.decode('utf-8').strip() container_user_key = docker.containers.list()[0].exec_run("cat {user_pub}".format(user_pub=UKEY["pub"])) \ .output.decode('utf-8').strip() self.assertEqual(get_plain_text(client.get('/ip/b')), container_ip) self.assertEqual(get_plain_text(client.get('/val+key/b')), container_val_key) self.assertEqual(get_plain_text(client.get('/user+key/b')), container_user_key) self.assertNotEqual(get_plain_text(client.get('/val+key/b')), get_plain_text(client.get('/user+key/b')))
def test_min_intersection_all_equal_depth_1(self, mock_get): # Fully connected, 5 quorums intersection_maps = [ {'a': {'b': {}, 'c': {"192.168.1.200:5000": 0}, 'd': {}, 'e': {}}, 'b': {'c': {}, 'd': {}, 'e': {}}, 'c': {'d': {}, 'e': {}}, 'd': {'e': {}}}, {'a': {'b': {}, 'c': {}, 'd': {"192.168.1.300:5000": 0}, 'e': {}}, 'b': {'c': {}, 'd': {}, 'e': {}}, 'c': {'d': {}, 'e': {}}, 'd': {'e': {}}}, {'a': {'b': {}, 'c': {}, 'd': {}, 'e': {"192.168.1.400:5000": 0}}, 'b': {'c': {}, 'd': {}, 'e': {}}, 'c': {'d': {}, 'e': {}}, 'd': {'e': {}}}, {'a': {'b': {}, 'c': {}, 'd': {}, 'e': {}}, 'b': {'c': {"192.168.1.500:5000": 0}, 'd': {}, 'e': {}}, 'c': {'d': {}, 'e': {}}, 'd': {'e': {}}}, {'a': {'b': {}, 'c': {}, 'd': {}, 'e': {}}, 'b': {'c': {}, 'd': {"192.168.1.600:5000": 0}, 'e': {}}, 'c': {'d': {}, 'e': {}}, 'd': {'e': {}}}, {'a': {'b': {}, 'c': {}, 'd': {}, 'e': {}}, 'b': {'c': {}, 'd': {}, 'e': {"192.168.1.700:5000": 0}}, 'c': {'d': {}, 'e': {}}, 'd': {'e': {}}} ] side_effects = [] for intersection_map in intersection_maps: res = Mock(spec=Response) res.text = json.dumps(intersection_map) res.status_code = 200 side_effects.append(res) mock_get.side_effect = side_effects app = api.create_app() app.config['TESTING'] = True app.config['DEBUG'] = False test_client = app.test_client() test_client.get('/start/a/b') test_client.post('/add/a', json=ADD_A_JSON) test_client.post('/add/b', json=ADD_B_JSON) time.sleep(1) res = test_client.get('/min+intersection/1') expected_intersection_map = { 'a': { 'b': {"localhost": 0}, 'c': {"192.168.1.200:5000": 0}, 'd': {"192.168.1.300:5000": 0}, 'e': {"192.168.1.400:5000": 0}}, 'b': { 'c': {"192.168.1.500:5000": 0}, 'd': {"192.168.1.600:5000": 0}, 'e': {"192.168.1.700:5000": 0}}, 'c': { 'd': {}, 'e': {}}, 'd': { 'e': {}} } self.assertEqual(res.get_json(), expected_intersection_map)
def setUp(self): """Define test variables and initialize app.""" database_filename = "src/test_database.db" project_dir = os.path.dirname(os.path.abspath(__file__)) database_path = "sqlite:///{}" \ .format(os.path.join(project_dir, database_filename)) self.app = create_app() self.client = self.app.test_client setup_db(self.app, database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() db_drop_and_create_all()
def setUp(self): """Define test variables and initialize app.""" project_dir = os.path.dirname(os.path.abspath(__file__)) self.app = create_app() self.client = self.app.test_client self.database_name = "drinks_test" self.database_path = "sqlite:///{}".format( os.path.join(project_dir, self.database_name)) setup_db(self.app, self.database_path) # Manager and Barista tokens self.barista_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlJFSTJNVFF3UXpoR1JEQTRRMFJETVVGRE5VTkJRVVUwUmtVNU9FUXhNMEUzTmtOQ016RkRSQSJ9.eyJpc3MiOiJodHRwczovL2ZzbmQtYmlsbHkuYXV0aDAuY29tLyIsInN1YiI6ImF1dGgwfDVkODYyYmY1NWJiZTgyMGRmN2EwNDQ5NyIsImF1ZCI6ImRyaW5rcyIsImlhdCI6MTU2OTI3NDUwNCwiZXhwIjoxNTY5MzYwOTA0LCJhenAiOiJybFVOaURqalMwQlA2bzBYSHJiNGYyU0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Z1WInaEuArh40n-bD84E3fDleczuxslGUSc873rQ6k_2kfI-IxUj-57iezSDmoGEXgUdexi_1sO2eyZ6F3En4Jj0Aka5p5rfps09Bro9uGYIitCFsTh_k7nuHi-KQE80ReZjIONtUNT-G-68tQ2yMyNqtM5Dmorvtb1f5Yw' # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all()
def test_forwarding_randomness(self, mock_post): # making test app and setting up test envi app = create_app() app.config['TESTING'] = True app.config['DEBUG'] = False app.config[QUORUMS]["a"] = [{ API_IP: "192.168.1.100", PORT: "5000", QUORUM_ID: "c" }, { API_IP: "192.168.1.200", PORT: "5000", QUORUM_ID: "c" }, { API_IP: "192.168.1.300", PORT: "5000", QUORUM_ID: "d" }, { API_IP: "192.168.1.400", PORT: "5000", QUORUM_ID: "e" }] mock_post.return_value = '<Response [200]>' selected_neighbours = [] for _ in range(10): forward(app, 'submit/', 'c', TRANSACTION_C_JSON) self.assertEqual(2, len(mock_post.call_args)) self.assertIn(mock_post.call_args[0][0], [ 'http://192.168.1.200:5000/submit/', 'http://192.168.1.100:5000/submit/' ]) self.assertEqual(TRANSACTION_C_JSON, mock_post.call_args[1]['json']) if mock_post.call_args[0][0] not in selected_neighbours: selected_neighbours.append(mock_post.call_args[0][0])\ self.assertEqual(len(selected_neighbours), 2)
from src.api import create_app from waitress import serve if __name__ == "__main__": application = create_app() serve(application, host="0.0.0.0", port=8000)
# -*- coding: utf-8 -*- """Create an application instance.""" from flask.helpers import get_debug_flag from src.api import create_app from src.settings import DevConfig, ProdConfig CONFIG = DevConfig if get_debug_flag() else ProdConfig app = create_app(CONFIG)
from __future__ import with_statement import sys from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig from src.models import * from src.core import db from src.api import create_app app = create_app() # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_offline():
import os from src.api import create_app app = create_app(os.environ["FLASK_CONFIG"])
from src.api import create_app app = create_app()
""" wsgi ~~~~ wsgi module """ from werkzeug.serving import run_simple from werkzeug.wsgi import DispatcherMiddleware from src import api APPLICATION = DispatcherMiddleware(None, { '/api': api.create_app() }) if __name__ == "__main__": run_simple('0.0.0.0', 5000, APPLICATION, use_reloader=True, use_debugger=True)
# -*- coding: utf-8 -*- """ manage ~~~~~~ Manager module """ from flask.ext.script import Manager from src.api import create_app from src.manage import CreateUserCommand, DeleteUserCommand, ListUsersCommand, UserAccessTokenCommand manager = Manager(create_app()) manager.add_command('create_user', CreateUserCommand()) manager.add_command('access_token', UserAccessTokenCommand()) manager.add_command('delete_user', DeleteUserCommand()) manager.add_command('list_users', ListUsersCommand()) if __name__ == "__main__": manager.run()
def create_app(self): self.temp_dir = tempfile.mkdtemp(suffix='bot-lax-api-test') cxx = api.create_app({'DEBUG': True, 'UPLOAD_FOLDER': self.temp_dir}) return cxx.app
def app(): os.environ["DATABASE_URL"] = "sqlite:///test.db" return create_app("testing")
def app(): flask_app = create_app(db_name="coffee_test.db") db_drop_and_create_all() yield flask_app
import os from src import logger from src.api import create_app logger.setLevel("INFO") env = os.getenv("FLASK_ENV") or "dev" print(f"Active environment: * {env} *") app = create_app(env)