def test_given_request_json(self): value = util.rand_string() _base_dir = util.rand_string() _format = 'JSON' _request_path = util.rand_string() def get_full_path(base_dir, format, req_or_resp, request_path): self.assertEquals(base_dir, _base_dir) self.assertEquals(format, _format.lower()) self.assertEquals(req_or_resp, 'request') self.assertEquals(request_path, _request_path) def get_file(*ignored_args, **ignored_kwargs): return '{"abc":"%s"}' % value with patch('zato.apitest.util.get_full_path', get_full_path): with patch('zato.apitest.util.get_file', get_file): self.ctx.zato.request.format = _format self.ctx.zato.request.is_json = True self.ctx.zato.environment_dir = _base_dir common.given_request(self.ctx, _request_path) self.assertEquals(self.ctx.zato.request.get('is_xml', INVALID), INVALID) self.assertEquals(self.ctx.zato.request.is_json, True) self.assertEquals(self.ctx.zato.request.data_impl['abc'], value)
def test_given_request_xml(self): value = util.rand_string() _base_dir = util.rand_string() _format = 'XML' _request_path = util.rand_string() def get_full_path(base_dir, format, req_or_resp, request_path): self.assertEquals(base_dir, _base_dir) self.assertEquals(format, _format.lower()) self.assertEquals(req_or_resp, 'request') self.assertEquals(request_path, _request_path) def get_file(*ignored_args, **ignored_kwargs): return '<abc>{}</abc>'.format(value) with patch('zato.apitest.util.get_full_path', get_full_path): with patch('zato.apitest.util.get_file', get_file): self.ctx.zato.request.format = _format self.ctx.zato.request.is_xml = True self.ctx.zato.environment_dir = _base_dir common.given_request(self.ctx, _request_path) self.assertEquals(self.ctx.zato.request.is_xml, True) self.assertEquals(self.ctx.zato.request.get('is_json', INVALID), INVALID) self.assertEquals(self.ctx.zato.request.data_impl.xpath('/abc')[0].text, value)
def setUp(self): # TODO: Cassandra tests are failing due to """PysandraUnitServerError: # Failed to execute command start: /127.0.0.1:7010 is in use by another process. # Change listen_address:storage_port in cassandra.yaml to values that do not conflict with other services""" return self.ctx = Bunch() self.ctx.zato = util.new_context(None, util.rand_string(), {}) import time time.sleep(2) # setup initial Cassandra keyspace self.current_session_name = util.rand_string() self.columns = ['userid', 'fname', 'sname'] self.values = util.rand_string(3) self.keyspace = util.rand_string() self.table = util.rand_string() data = (self.keyspace, self.table) + tuple(s for s in self.columns) keyspace_statement = ( "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 }") % self.keyspace table_statement = ("CREATE TABLE %s.%s (%s text PRIMARY KEY, %s text, %s text)") % data self.embedded_cassandra = pysandraunit.PysandraUnit(native_transport_port=9042) self.embedded_cassandra.start() self.cluster = Cluster(protocol_version=1) self.session = self.cluster.connect() self.session.execute(keyspace_statement) self.session.execute(table_statement) self.cluster.shutdown() # setup Cassandra ctx cassandra_.given_cassandra_contact_points(self.ctx, 'localhost') cassandra_.given_cassandra_protocol_version(self.ctx, 1) cassandra_.given_cassandra_port(self.ctx, '9042') cassandra_.given_i_connect_to_keyspace_as_session(self.ctx, self.keyspace, self.current_session_name)
def setUp(self): self.ctx = Bunch() self.ctx.zato = util.new_context(None, util.rand_string(), {}) # setup initial Cassandra keyspace self.current_session_name = util.rand_string() self.columns = ['userid', 'fname', 'sname'] self.values = util.rand_string(3) self.keyspace = util.rand_string() self.table = util.rand_string() data = (self.keyspace, self.table) + tuple(s for s in self.columns) keyspace_statement = ( "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 }") % self.keyspace table_statement = ("CREATE TABLE %s.%s (%s text PRIMARY KEY, %s text, %s text)") % data self.embedded_cassandra = pysandraunit.PysandraUnit(native_transport_port=9042) self.embedded_cassandra.start() self.cluster = Cluster(protocol_version=1) self.session = self.cluster.connect() self.session.execute(keyspace_statement) self.session.execute(table_statement) self.cluster.shutdown() # setup Cassandra ctx cassandra_.given_cassandra_contact_points(self.ctx, 'localhost') cassandra_.given_cassandra_protocol_version(self.ctx, 1) cassandra_.given_cassandra_port(self.ctx, '9042') cassandra_.given_i_connect_to_keyspace_as_session(self.ctx, self.keyspace, self.current_session_name)
def test_given_i_store_sql_query_result_under_name_multi_elem_list(self): id = util.rand_int() name = util.rand_string() value = util.rand_string() self.cursor.execute("INSERT INTO TestDB (id, name, value) VALUES (?,?,?)", (id, name, value)) self.conn.commit() q = 'SELECT name FROM TestDb' sql.given_i_store_sql_query_result_under_name(self.ctx, q, 'sql_result_multi', self.general_conn) self.assertEquals(self.ctx.zato.user_ctx['sql_result_multi'], [(self.name,), (name,)])
def test_i_insert_data_from_csv_file_to_cassandra_table(self, open_mock): values = (util.rand_string(), util.rand_string(), util.rand_string()) fake_csv = 'userid, fname, sname\n%s, %s, %s' % values filename = util.rand_string() open_mock.return_value = StringIO(fake_csv) cassandra_.i_insert_data_from_csv_file_to_cassandra_table(self.ctx, filename, self.table, self.current_session_name) statement = "SELECT * FROM %s" % self.table cassandra_.given_i_store_cql_query_result_under_name(self.ctx, statement, 'cql_result', self.current_session_name, 0) self.assertEquals(self.ctx.zato.user_ctx['cql_result'], ';'.join(values))
def test_given_i_store_zato_info_under_conn_name(self): conn_name = util.rand_string() cluster_id = util.rand_int() url_path = util.rand_string() username = util.rand_string() password = util.rand_string() zato_.given_i_store_zato_info_under_conn_name(self.ctx, cluster_id, url_path, username, password, conn_name) stored = self.ctx.zato.user_ctx[conn_name] for key in stored: self.assertEquals(stored[key], eval(key))
def test_i_create_table_and_insert_data_from_csv_file_using_types_and_header(self, open_mock): values = (util.rand_string(), util.rand_int(), util.rand_string()) fake_csv = 'a-text, b:integer, c/varchar:30\n%s, %s, %s' % values kwargs = {'filename': util.rand_string(), 'tablename': util.rand_string(), 'conn_name': self.conn} open_mock.return_value = StringIO(fake_csv) sql.insert_csv(use_header=1, use_types=1, **kwargs) q = self.conn.execute('SELECT * FROM {tn}'.format(tn = kwargs['tablename'])) result = q.fetchone() self.assertEquals(result, values)
def test_i_create_table_and_insert_data_from_csv_file(self, open_mock): values = (util.rand_string(), util.rand_string(), util.rand_string()) fake_csv = '%s, %s, %s' % values kwargs = {'filename': util.rand_string(), 'tablename': util.rand_string(), 'conn_name': self.conn} open_mock.return_value = StringIO(fake_csv) sql.insert_csv(use_types='default', **kwargs) q = self.conn.execute('SELECT * FROM {tn}'.format(tn = kwargs['tablename'])) result = q.fetchone() self.assertEquals(result, values)
def test_i_insert_data_from_csv_file(self, open_mock): values = (util.rand_int(), util.rand_string(), util.rand_string()) fake_csv = 'id, name, value\n%s, %s, %s' % values kwargs = {'filename': util.rand_string(), 'tablename': 'TestDB', 'conn_name': self.general_conn} open_mock.return_value = StringIO(fake_csv) sql.insert_csv(use_header=1, **kwargs) q = self.general_conn.execute('SELECT * FROM TestDB') result = q.fetchall()[1] self.assertEquals(result, values)
def test_i_create_table_and_insert_data_from_csv_file_using_header(self, open_mock): colnames = (tuple((element) for element in util.rand_string(5))) values = (util.rand_string(), util.rand_string(), util.rand_int(), round(util.rand_float(), 4), util.rand_string()) t = colnames + values fake_csv = '%s, %s, %s, %s, %s\ntext, varchar:30, integer, float, char\n%s, %s, %s, %s, %s' % t kwargs = {'filename': util.rand_string(), 'tablename': util.rand_string(), 'conn_name': self.conn} open_mock.return_value = StringIO(fake_csv) sql.insert_csv(use_header=1, use_types=0, **kwargs) q = self.conn.execute('SELECT * FROM {tn}'.format(tn = kwargs['tablename'])) result = q.fetchone() self.assertEquals(result, values)
def test_i_insert_data_from_csv_file_to_cassandra_table(self, open_mock): # TODO: Cassandra tests are failing due to """PysandraUnitServerError: # Failed to execute command start: /127.0.0.1:7010 is in use by another process. # Change listen_address:storage_port in cassandra.yaml to values that do not conflict with other services""" return values = (util.rand_string(), util.rand_string(), util.rand_string()) fake_csv = 'userid, fname, sname\n%s, %s, %s' % values filename = util.rand_string() open_mock.return_value = StringIO(fake_csv) cassandra_.i_insert_data_from_csv_file_to_cassandra_table(self.ctx, filename, self.table, self.current_session_name) statement = "SELECT * FROM %s" % self.table cassandra_.given_i_store_cql_query_result_under_name(self.ctx, statement, 'cql_result', self.current_session_name, 0) self.assertEquals(self.ctx.zato.user_ctx['cql_result'], ';'.join(values))
def test_new_context_from_environment_dir(self): # Same comment as in test_new_context_from_old_ctx. for x in range(2): environment_dir = rand_string() ctx = new_context(None, environment_dir, {}) self._test_new_context(ctx, environment_dir)
def test_given_request_xml_no_data(self): class _RequestPath(object): def __init__(self): self.value = util.rand_string() def __nonzero__(self): return False _base_dir = util.rand_string() _format = 'XML' _request_path = _RequestPath() def get_full_path(base_dir, format, req_or_resp, request_path): self.assertEquals(base_dir, _base_dir) self.assertEquals(format, _format.lower()) self.assertEquals(req_or_resp, 'request') self.assertEquals(request_path.value, _request_path.value) def get_file(*ignored_args, **ignored_kwargs): pass with patch('zato.apitest.util.get_full_path', get_full_path): with patch('zato.apitest.util.get_file', get_file): self.ctx.zato.request.format = 'XML' self.ctx.zato.environment_dir = _base_dir self.assertRaises(ValueError, common.given_request, self.ctx, _request_path)
def test_given_json_pointer_is_rand_date_between(self): path = util.rand_string() date_start = (datetime.now().strftime('%Y-%m-%d')) date_end = (datetime.now() + relativedelta(months=6)).strftime('%Y-%m-%d') json.given_json_pointer_is_rand_date_between(self.ctx, '/' + path, date_start, date_end, 'default') rand_date_between = datetime.strptime(self.ctx.zato.request.data_impl[path], '%Y-%m-%dT%H:%M:%S') self.assertLess(datetime.strptime(date_start, '%Y-%m-%d'), rand_date_between) self.assertGreater(datetime.strptime(date_end, '%Y-%m-%d'), rand_date_between)
def test_when_the_url_is_invoked_xml(self): data = '<a><b>cc</b></a>' data_impl = etree.fromstring(data) data_c14n = xml_c14nize(data_impl) method = 'POST' address = 'http://{}.example.com'.format(util.rand_string()) url_path = '/{}'.format(util.rand_string()) qs = '?{}={}'.format(*util.rand_string(2)) headers = {util.rand_string():util.rand_string(), util.rand_string():util.rand_string()} ctx = Bunch(zato=Bunch(request=Bunch())) ctx.zato.request.is_xml = True ctx.zato.request.data_impl = data_impl ctx.zato.request.method = method ctx.zato.request.address = address ctx.zato.request.url_path = url_path ctx.zato.request.qs = qs ctx.zato.request.headers = headers common.when_the_url_is_invoked(ctx, [XMLEchoAdapter(b'<dummy/>')]) sent_request = loads(etree.fromstring(ctx.zato.response.data.text).xpath('/response')[0].text) # Confirms the headers we sent were received. for key, value in headers.items(): self.assertEquals(sent_request['request']['headers'][key], value) # Confirms the body we sent was received. self.assertEquals(xml_c14nize(sent_request['request']['data']), data_c14n)
def test_when_the_url_is_invoked_json(self): data_impl = {'a': {'b': 'cc'}} method = 'POST' address = 'http://{}.example.com'.format(util.rand_string()) url_path = '/{}'.format(util.rand_string()) qs = '?{}={}'.format(*util.rand_string(2)) headers = {util.rand_string():util.rand_string(), util.rand_string():util.rand_string()} ctx = Bunch(zato=Bunch(request=Bunch())) ctx.zato.request.is_xml = False ctx.zato.request.is_json = True ctx.zato.request.response_format = 'JSON' ctx.zato.request.data_impl = data_impl ctx.zato.request.method = method ctx.zato.request.address = address ctx.zato.request.url_path = url_path ctx.zato.request.qs = qs ctx.zato.request.headers = headers common.when_the_url_is_invoked(ctx, [JSONEchoAdapter({})]) sent_request = loads(ctx.zato.response.data_impl['data']) # Confirms the headers we sent were received. for key, value in headers.items(): self.assertEquals(sent_request['request']['headers'][key], value) # Confirms the body we sent was received. self.assertDictEqual(loads(sent_request['request']['data']), data_impl)
def test_new_context_from_old_ctx(self): # Done twice to ensure that util's context actually is wiped out. for x in range(2): environment_dir = rand_string() old_ctx = Bunch() old_ctx.zato = Bunch(environment_dir=environment_dir) ctx = new_context(old_ctx, None, {}) self._test_new_context(ctx, environment_dir)
def test_given_request_is(self): _ctx, _data = util.rand_string(2) def given_request_impl(ctx, data): self.assertEquals(ctx, _ctx) self.assertEquals(data, _data) with patch('zato.apitest.steps.common.given_request_impl', given_request_impl): common.given_request_is(_ctx, _data)
def test_given_request_impl_xml(self): value = util.rand_string() data = '<abc>{}</abc>'.format(value) self.ctx.zato.request.format = 'XML' self.ctx.zato.request.is_xml = True common.given_request_impl(self.ctx, data) self.assertEquals(self.ctx.zato.request.is_xml, True) self.assertEquals(self.ctx.zato.request.get('is_json', INVALID), INVALID) self.assertEquals(self.ctx.zato.request.data_impl.xpath('/abc')[0].text, value)
def test_given_request_impl_json(self): value = util.rand_string() data = '{"abc":"%s"}' % value self.ctx.zato.request.format = 'JSON' self.ctx.zato.request.is_json = True common.given_request_impl(self.ctx, data) self.assertEquals(self.ctx.zato.request.get('is_xml', INVALID), INVALID) self.assertEquals(self.ctx.zato.request.is_json, True) self.assertEquals(self.ctx.zato.request.data_impl['abc'], value)
def setUp(self): self.ctx = Bunch() self.ctx.zato = util.new_context(None, util.rand_string(), {}) self.id = util.rand_int() self.name = util.rand_string() self.value = util.rand_string() self.temp_db = NamedTemporaryFile().name self.conn = sqlite3.connect(self.temp_db) self.cursor = self.conn.cursor() self.cursor.execute("CREATE TABLE TestDB (id integer, name text, value text)") self.cursor.execute("INSERT INTO TestDB (id, name, value) VALUES (?,?,?)", (self.id, self.name, self.value)) self.conn.commit() self.sqlalchemy_url = 'sqlite:///' + self.temp_db general_conn_name = 'general_connn_name' sql.given_i_connect_to_sqlalchemy_url_as_conn_name(self.ctx, self.sqlalchemy_url, general_conn_name) self.general_conn = self.ctx.zato.user_ctx[general_conn_name]
def test_then_context_is_cleaned_up(self): _ctx = Bunch() _ctx.zato = util.rand_string() def new_context(ctx, environment_dir): self.assertDictEqual(ctx, _ctx) self.assertIsNone(environment_dir) with patch('zato.apitest.util.new_context', new_context): common.then_context_is_cleaned_up(_ctx)
def test_when_the_url_is_invoked_form(self): form = {'key1': ['value1'], 'key2': ['value2']} method = 'POST' address = 'http://{}.example.com'.format(util.rand_string()) url_path = '/{}'.format(util.rand_string()) headers = {util.rand_string():util.rand_string(), util.rand_string():util.rand_string()} ctx = Bunch(zato=Bunch(request=Bunch())) ctx.zato.request.is_xml = False ctx.zato.request.is_json = False ctx.zato.request.is_raw = False ctx.zato.request.is_form = True ctx.zato.request.request_format = 'FORM' ctx.zato.request.response_format = 'JSON' ctx.zato.request.form = form ctx.zato.request.data_impl = None ctx.zato.request.method = method ctx.zato.request.address = address ctx.zato.request.url_path = url_path ctx.zato.request.qs = '' ctx.zato.request.headers = headers common.when_the_url_is_invoked(ctx, [JSONEchoAdapter({})]) sent_request = loads(ctx.zato.response.data_impl['data']) # Confirms the headers we sent were received. for key, value in headers.items(): self.assertEquals(sent_request['request']['headers'][key], value) # Confirms the form data we sent was received. self.assertDictEqual(urlparse.parse_qs(sent_request['request']['data']), form)
def setUp(self): self.ctx = Bunch() self.ctx.zato = util.new_context(None, util.rand_string(), {}) self.fake_service_code = util.rand_string() conn_name = util.rand_string() cluster_id = util.rand_int() url_path = util.rand_string() username = util.rand_string() password = util.rand_string() zato_.given_i_store_zato_info_under_conn_name(self.ctx, cluster_id, url_path, username, password, conn_name) self.stored = self.ctx.zato.user_ctx[conn_name]
def test_given_header(self): header, value = util.rand_string(2) common.given_header(self.ctx, header, value) self.assertEquals(self.ctx.zato.request.headers[header], value)
def test_given_user_agent_is(self): value = util.rand_string() common.given_user_agent_is(self.ctx, value) self.assertEquals(self.ctx.zato.request.headers['User-Agent'], value)
def test_then_json_pointer_is_one_of(self): path, value = util.rand_string(2) self.ctx.zato.response.data_impl[path] = util.rand_string() self.assertRaises(AssertionError, json.then_json_pointer_is_one_of, self.ctx, '/' + path, value)
def __init__(self): self.value = util.rand_string()
def setUp(self): self.ctx = Bunch() self.ctx.zato = util.new_context(None, util.rand_string(), {})
def test_given_json_pointer_in_request_is_one_of(self): path = util.rand_string() value = ''.join((path, util.rand_string())) json.given_json_pointer_in_request_is_one_of(self.ctx, '/' + path, value) self.assertEquals(self.ctx.zato.request.data_impl[path], util.any_from_list(value))
def test_then_header_starts_with_not_ok(self): name, prefix = util.rand_string(2) actual = prefix + util.rand_string() self.ctx.zato.response.data.headers[name] = actual self.assertRaises(AssertionError, common.then_header_starts_with, self.ctx, name, util.rand_string())
def test_given_url_path(self): value = util.rand_string() common.given_url_path(self.ctx, value) self.assertEquals(self.ctx.zato.request.url_path, value)
def test_then_header_isnt_empty_ok(self): name = util.rand_string() actual = util.rand_string() self.ctx.zato.response.data.headers[name] = actual self.assertTrue(common.then_header_isnt_empty(self.ctx, name))
def test_then_header_starts_with_ok(self): name, prefix = util.rand_string(2) actual = prefix + util.rand_string() self.ctx.zato.response.data.headers[name] = actual self.assertTrue(common.then_header_starts_with(self.ctx, name, prefix))
def test_then_header_is_empty_not_ok(self): name = util.rand_string() actual = util.rand_string() self.ctx.zato.response.data.headers[name] = actual self.assertRaises(AssertionError, common.then_header_is_empty, self.ctx, name)
def test_then_header_doesnt_exist_ok(self): name = util.rand_string() actual = util.rand_string() self.ctx.zato.response.data.headers[name] = actual self.assertTrue( common.then_header_doesnt_exist(self.ctx, util.rand_string()))
def test_then_header_contains_ok(self): name = util.rand_string() substring = util.rand_string() actual = substring + util.rand_string() self.ctx.zato.response.data.headers[name] = actual self.assertTrue(common.then_header_contains(self.ctx, name, substring))
def test_given_format(self): value = util.rand_string() common.given_format(self.ctx, value) self.assertEquals(self.ctx.zato.request.format, value)
def setUp(self): self.ctx = Bunch() self.ctx.zato = util.new_context(None, util.rand_string(), {}) self.ctx.zato.response = Bunch() self.ctx.zato.response.data = Bunch() self.ctx.zato.response.data_impl = Bunch()
def test_given_http_method(self): value = util.rand_string() common.given_http_method(self.ctx, value) self.assertEquals(self.ctx.zato.request.method, value)
def test_then_json_pointer_is_an_integer(self): path = util.rand_string() value = util.rand_int() self.ctx.zato.response.data_impl[path] = value + 1 self.assertRaises(AssertionError, json.then_json_pointer_is_an_integer, self.ctx, '/' + path, value)
def test_given_address(self): value = util.rand_string() common.given_address(self.ctx, value) self.assertEquals(self.ctx.zato.request.address, value)
def test_then_json_pointer_isnt_empty(self): path = util.rand_string() self.ctx.zato.response.data_impl[path] = '' self.assertRaises(AssertionError, json.then_json_pointer_isnt_empty, self.ctx, '/')
def test_given_query_string(self): value = util.rand_string() common.given_query_string(self.ctx, value) self.assertEquals(self.ctx.zato.request.query_string, value)
def test_given_json_pointer_is_rand_date_non_default_format(self): path = util.rand_string() self.ctx.zato.date_formats['new'] = 'YY-DD-MM' json.given_json_pointer_is_rand_date(self.ctx, '/' + path, 'new') assert datetime.strptime(self.ctx.zato.request.data_impl[path], '%y-%d-%m')
def test_given_json_pointer_in_request_is_a_random_float(self): path = util.rand_string() json.given_json_pointer_in_request_is_a_random_float(self.ctx, '/' + path) self.assertIs(type(self.ctx.zato.request.data_impl[path]), float)
def test_given_i_store_value_under_name(self): value, name = util.rand_string(2) common.given_i_store_value_under_name(self.ctx, value, name) self.assertEquals(self.ctx.zato.user_ctx[name], value)
def test_given_json_pointer_is_rand_date_default_format(self): path = util.rand_string() json.given_json_pointer_is_rand_date(self.ctx, '/' + path, 'default') assert datetime.strptime(self.ctx.zato.request.data_impl[path], '%Y-%m-%dT%H:%M:%S')
def test_then_status_is_needs_an_int(self): expected = util.rand_string() actual = util.rand_int() self.ctx.zato.response.data.status_code = actual self.assertRaises(ValueError, common.then_status_is, self.ctx, expected)
def test_given_json_pointer_is_utc_now(self): path = util.rand_string() json.given_json_pointer_is_utc_now(self.ctx, '/' + path, 'default') utc_now = datetime.strptime(self.ctx.zato.request.data_impl[path], '%Y-%m-%dT%H:%M:%S') timedelta_threshold = 50 # microseconds self.assertLessEqual((datetime.now() - utc_now).seconds * 10**-3, timedelta_threshold)
def test_then_header_isnt_ok(self): name = util.rand_string() expected, actual = util.rand_string(2) self.ctx.zato.response.data.headers[name] = actual self.assertTrue(common.then_header_isnt(self.ctx, name, expected))