def vehicle(v): world.vehicle_type = [] logger.info("guesstype %s", guess_types(v.hashes)) for v in guess_types(v.hashes): r = requests.post(f"{config.api_uri}/caravan/suitable_vehicle", json=v, headers={"APIToken": config.client.api_token, "USERToken": world.token}) world.vehicle_response = r.json() # logger.debug("Response for suitable vehicle is: %s", world.vehicle_response) world.vehicle_type = list(world.vehicle_response["vehicle_models"].keys()) # logger.info("response for vehicle type is: %s", world.vehicle_type) world.vehicle_options = list(world.vehicle_response["vehicle_options"].values()) # logger.info("response for option is: %s", world.vehicle_options) world.vehicle_options_final = [] for x in world.vehicle_options: final_option = list(x.keys()) # logger.info("final option list is : %s", final_option) for item in final_option: if item != '': world.vehicle_options_final.append(item)
def create_urls(self): url_hashes = guess_types(self.hashes) if url_hashes: has_visit_count = True if 'visit_count' in url_hashes[0] else False for url_hash in guess_types(self.hashes): url = URL( original_url=url_hash['original_url'], key=url_hash['key'], title=url_hash['title'], visit_count=url_hash['visit_count'] if has_visit_count else 0) url = url.save()
def test_hashes(self): """Test step.hashes structure""" input_ = [{"name": "Danni", "height": "178"}, {"name": "Alexey", "height": "182"}] output_ = [{"name": "Danni", "height": 178}, {"name": "Alexey", "height": 182}] self.assertEqual(guess_types(input_), output_)
def vehicle(d): for d in guess_types(d.hashes): r = requests.post(f"{config.api_uri}/caravan/suitable_vehicle", json=d, headers={"APIToken": config.client.api_token, "USERToken": world.token}) # logger.info("d is: %s", d) world.vehicle_response = r.json() # logger.debug("Response for suitable vehicle is: %s", world.vehicle_response) world.vehicle_dimension = list(world.vehicle_response["truck_dimensions"].values()) logger.info("truck dimensions are : %s", world.vehicle_dimension) world.weight_in_list = d['weight_load'] # logger.info("the weight in list is : %s", world.weight_in_list) world.length_in_list = d['length_load'] # logger.info("the length in list is : %s", world.length_in_list) world.width_in_list = d['width_load'] world.height_in_list = d['height_load'] world.length_list = [] world.width_list = [] world.height_list = [] for i in world.vehicle_dimension: for m in i['length']: world.length_list.append(float(m)) # logger.info("length list is %s", world.length_list) for n in i['width']: world.width_list.append(float(n)) # logger.info("width list is %s", world.width_list) for p in i['height']: world.height_list.append(float(p))
def _create_models_for_relation_step(self, rel_model_name, rel_key, rel_value, model): """ Create a new model linked to the given model. Syntax: And `model` with `field` "`value`" has `new model` in the database: Example: .. code-block:: gherkin And project with name "Ball Project" has goals in the database: | description | | To have fun playing with balls of twine | """ model = get_model(model) lookup = {rel_key: rel_value} rel_model = get_model(rel_model_name).objects.get(**lookup) data = guess_types(self.hashes) for hash_ in data: hash_['%s' % rel_model_name] = rel_model try: func = _WRITE_MODEL[model] except KeyError: func = partial(write_models, model) func(data, None)
def add_order(s): world.list_of_status = [] for s in guess_types(s.hashes): cur = (datetime.now() + timedelta(days=1)) s['dispatch_date'] = str(JalaliDate(cur.date())) s['dispatch_hour'] = cur.time().strftime('%H:%M') logger.info(s['dispatch_date']) logger.info(s['dispatch_hour']) logger.info(" sssssss is : %s", s) r = requests.post(f"{config.api_uri}/caravan/add_order/", json=s, headers={ "APIToken": config.client.api_token, "USERToken": world.token }) world.res = r.json() logger.info("Response: %s", str(world.res).encode('utf-8')) world.status = r.status_code world.track_code = world.res['order_data']['tracking_code'] logger.info("tracking code groups : %s", world.track_code) logger.info(" s is : %s", s) world.list_of_status.append(world.res['order_data']['status']) logger.info("wwwwwwww list of status of orders is %s", world.list_of_status) time.sleep(1)
def add_cities(self): results = list() for row in tools.guess_types(self.hashes): res = requests.post(f"{config.base_api_uri}/cities", json=row) results.append(res.status_code) world.cities = results logger.info(world.cities)
def add_order_admin(s): world.order_price = [] world.success = [] for s in guess_types(s.hashes): cur = (datetime.now() + timedelta(days=1)) s['dispatch_date'] = str(JalaliDate(cur.date())) s['dispatch_hour'] = cur.time().strftime('%H:%M') logger.info(s['dispatch_date']) logger.info(s['dispatch_hour']) r = requests.post(f"{config.api_uri}/caravan/add_order", json=s, headers={ "APIToken": config.admin.api_token, "USERToken": config.admin.user_token }) logger.error(r.text) world.res = r.json() time.sleep(1) logger.info("Response: %s", str(world.res).encode('utf-8')) world.status = r.status_code world.order_price.append(world.res['order_data']['price']) logger.info("order price isss %s", world.order_price) world.success.append(world.res["success_flag"]) logger.info("world order price is : %s", world.order_price) logger.info("the worldsuccess is : %s", world.res["success_flag"])
def test_table(self): """Test step.table structure""" input_ = [["name", "russian", "german"], ["Danni", "false", "true"], ["Alexey", "true", "false"]] output_ = [["name", "russian", "german"], ["Danni", False, True], ["Alexey", True, False]] self.assertEqual(guess_types(input_), output_)
def create_user(data, field=None): """Create users setting the password.""" if field: return write_models(User, data, field=field) data = guess_types(data) for hash_ in data: is_superuser = hash_.pop('is_superuser', False) is_staff = None if is_superuser: if 'email' not in hash_: hash_['email'] = '*****@*****.**' if 'password' not in hash_: hash_['password'] = '******' if 'is_staff' in hash_: del hash_['is_staff'] user = User.objects.create_superuser(**hash_) else: is_staff = hash_.pop('is_staff', None) if 'username' not in hash_: hash_['username'] = \ hashlib.md5(hash_['email']).hexdigest()[:30] if 'email' not in hash_: hash_['email'] = '*****@*****.**' % (hash_['username']) user = User.objects.create_user(**hash_) if is_staff is not None: user.is_staff = is_staff user.save() reset_sequence(User)
def check_unique_facility(self): results = list() for row in tools.guess_types(self.hashes): res = requests.post(f"{config.base_api_uri}/facilities", json=row) results.append(res.status_code) world.unique_facility = results logger.info(world.unique_facility)
def check_updated_facilities(self, facility_slug: str): rows = tools.guess_types(self.hashes) logger.info(rows) res = requests.get(f"{config.base_api_uri}/facilities/{facility_slug}") result2 = res.json() logger.info(result2) assert all((rows[0][key] == result2[key] for key in rows[0]))
def step_create_friendships(self): Friendship.objects.bulk_create([ Friendship(id=data['id'], user1=User.objects.get(id=data['user1']), user2=User.objects.get(id=data['user2']), status=data['status']) for data in guess_types(self.hashes) ])
def step_create_transactions(self): Transaction.objects.bulk_create([ Transaction( user=User.objects.get(id=data['user']), amount=data['amount'], type_of_transaction=data['type_of_transaction'] ) for data in guess_types(self.hashes) ])
def update_facility(self, facility_slug: str): row = tools.guess_types(self.hashes)[0] logger.info(row) res = requests.put(f"{config.base_api_uri}/facilities/{facility_slug}", json=row) logger.info(res.text) world.put_facility = res.status_code logger.info(world.put_facility)
def update_map_set(step, setkey, key): m = world.store[key] setkey = '{0}_set'.format(setkey) for value in guess_types(step.hashes): m[setkey].add(value['Value']) world.store[key] = m
def checklist_city_modified(self, slug: str): rows = tools.guess_types(self.hashes) logger.info(rows) res = requests.get(f"{config.base_api_uri}/cities/{slug}", headers={"Accept-Language":"en-US"}) logger.info(res.json()) result2 = res.json() logger.info(result2) assert all((rows[0][key] == result2[key] for key in rows[0]))
def add_zone_data_entry(self, city_slug: str): results = list() for row in tools.guess_types(self.hashes): res = requests.post(f"{config.base_api_uri}/cities/{city_slug}/zones", json=row) results.append(res.status_code) world.data_entry_zone = results logger.info(world.data_entry_zone)
def add_facilities(self): call.delete_facilities() results = list() for row in tools.guess_types(self.hashes): logger.info(row) res = requests.post(f"{config.base_api_uri}/facilities", json=row) results.append(res.status_code) world.post_facilities = results logger.info(world.post_facilities)
def edit_offices(self, city_slug: str, office_slug): row = tools.guess_types(self.hashes)[0] location = json.loads(geojson.dumps(Point(*map(float, row["location"].split(","))))) row['location'] = location logger.info(row) res = requests.put(f"{config.base_api_uri}/cities/{city_slug}/offices/{office_slug}", json=row) logger.info(res.text) world.put_offices = res.status_code logger.info(world.put_offices)
def feed_initial_data(step): for entry in guess_types(step.hashes): key = entry['Key'] doc = { 'field1': entry['Field1'], 'field2': entry['Field2'] } world.store[key] = doc
def check_users(self): """Look for users in my user list""" expected = guess_types(self.hashes) actual = [{"username": obj.username, "email": obj.email} for obj in User.users] print(actual) assert_equal(expected, actual)
def check_facilities_added(self, facility_slug): rows = tools.guess_types(self.hashes) logger.info(rows) res = requests.get(f"{config.base_api_uri}/facilities/{facility_slug}", headers={"Accept-Language": "en-US"}) logger.info(res.json()) result2 = res.json() logger.info(result2) assert all((rows[0][key] == result2[key] for key in rows[0]))
def modified_zones_list(self, city_slug: str, slug: str): rows = tools.guess_types(self.hashes) logger.info(rows) res = requests.get( f"{config.base_api_uri}/cities/{city_slug}/zones/{slug}", headers={"Accept-Language": "en-US"}) result2 = res.json() logger.info(result2) # logger.info(tuple((key for key in rows[0] if rows[0][key] != result2[key]))) assert all((rows[0][key] == result2[key] for key in rows[0]))
def modified_city_services(self, city_slug: str, services_slug: str): rows = tools.guess_types(self.hashes) logger.info(rows) res = requests.get( f"{config.base_api_uri}/cities/{city_slug}/services/{services_slug}/details", headers={"Accept-Language": "en-US"}) logger.info(res.json()) result2 = res.json() logger.info(result2) assert all((rows[0][key] == result2[key] for key in rows[0]))
def check_agencies(self): """Look for agencies in my agency list""" expected = guess_types(self.hashes) actual = [{ 'name': obj.name, } for obj in Agency.agencies] print(actual) assert_equal(expected, actual)
def vehicle_type(t): world.vehicle_type_should_be = [] for t in guess_types(t.hashes): world.vehicle_type_should_be.append(t) # logger.info("the vehicle should be: %s", world.vehicle_type_should_be) for x in world.vehicle_type_should_be: final_vehicle_list = list(x.values()) # logger.info("final sort is : %s", final_vehicle_list) assert world.vehicle_type == final_vehicle_list
def add_data_for_category(self, category_slug: str): result = list() for row in tools.guess_types(self.hashes): link = row["service_slug"] res = requests.put( f"{config.base_api_uri}/categories/{category_slug}/services/{link}" ) logger.info(res.status_code) result.append(res.status_code) world.add_data_category_services = result logger.info(world.add_data_category_services)
def write_pandas(data, field): # It is not necessary to call hashes_data/guess_types, but it might be # present in old code using the library. Test that it is a no-op # in that case. data = guess_types(data) for hash_ in data: if 'name' in hash_: hash_['name'] += ' Panda' return write_models(Panda, data, field)
def check_result_filter_tags(self): rows = list() for row in tools.guess_types(self.hashes): filed = row["tags"].split(",") row["tags"] = filed rows.append(row) logger.info(rows) result2 = world.tags_filter_data['value'] logger.info(result2) logger.info( tuple((key for key in rows[0] if rows[0][key] != result2[0][key]))) assert all((rows[0][key] == result2[0][key] for key in rows[0]))
def check_users(self): """Look for users in my user list""" expected = guess_types(self.hashes) actual = [{ 'username': obj.username, 'email': obj.email, } for obj in User.users] print(actual) assert_equal(expected, actual)
def check_services_modified(self, slug: str): table = tools.guess_types(self.hashes) chk = list() for row in table: filed = row["tags"].split(",") row['tags'] = filed chk.append(row) logger.info(chk) res = requests.get(f"{config.base_api_uri}/services/{slug}") result2 = res.json() logger.info(result2) # logger.info(tuple((k for k in chk[0] if chk[0][k] != result2[k]))) assert all((chk[0][k] == result2[k] for k in chk[0]))
def check_offices_edited(self, city_slug, slug: str): table = tools.guess_types(self.hashes) l = list() for row in table: location = json.loads(geojson.dumps(Point(*map(float, row["location"].split(","))))) row['location'] = location logger.info(row) l.append(row) res = requests.get(f"{config.base_api_uri}/cities/{city_slug}/offices/{slug}") result2 = res.json() logger.info(result2) logger.info(tuple((k for k in l[0] if l[0][k] != result2[k]))) assert all((l[0][key] == result2[key] for key in l[0]))
def show_price(m): final_price = [] for m in guess_types(m.hashes): final_price.append(m) logger.debug(final_price) price_value = [x.get('price') for x in final_price[0:5]] float_list = [float(i) for i in price_value] logger.debug(float_list) final_list = [str(a) for a in float_list] logger.debug(final_list) assert final_list == world.order_price
def _write_models_step(self, model, field=None): """ Write or update a model. """ model = get_model(model) data = guess_types(self.hashes) try: func = _WRITE_MODEL[model] except KeyError: func = partial(write_models, model) func(data, field)
def test_table(self): """Test step.table structure""" input_ = [ ['name', 'russian', 'german'], ['Danni', 'false', 'true'], ['Alexey', 'true', 'false'], ] output_ = [ ['name', 'russian', 'german'], ['Danni', False, True], ['Alexey', True, False], ] self.assertEqual(guess_types(input_), output_)
def query_index(step, search): result = world.feature.search(search) riak_keys = [ doc[world.feature.DATA_ID] for doc in result ] expected = [ item['Key'] for item in guess_types(step.hashes) ] assert len(expected) == len(riak_keys) for key in expected: assert key in riak_keys
def _model_exists_step(self, model, should_exist): """ Test for the existence of a model matching the given data. """ model = get_model(model) data = guess_types(self.hashes) queryset = model.objects try: existence_check = _TEST_MODEL[model] except KeyError: existence_check = test_existence failed = 0 try: for hash_ in data: match = existence_check(queryset, hash_) if should_exist: assert match, \ "%s does not exist: %s" % (model.__name__, hash_) else: assert not match, \ "%s exists: %s" % (model.__name__, hash_) except AssertionError as exc: print(exc) failed += 1 if failed: print("Rows in DB are:") for existing_model in queryset.all(): _dump_model(existing_model, attrs=[k[1:] for k in data[0].keys() if k.startswith('@')]) if should_exist: raise AssertionError("%i rows missing" % failed) else: raise AssertionError("%i rows found" % failed)
def test_hashes(self): """Test step.hashes structure""" input_ = [{ 'name': 'Danni', 'height': '178', }, { 'name': 'Alexey', 'height': '182', }] output_ = [{ 'name': 'Danni', 'height': 178, }, { 'name': 'Alexey', 'height': 182, }] self.assertEqual(guess_types(input_), output_)
def _run_factory(factory, self, count=None): """ Run a factory using the step definition. """ count = 1 if count is None else int(count) if self.table: headers = self.table[0] rows = tuple( dict(zip(headers, row)) for row in guess_types(self.table[1:]) ) else: rows = ({},) if count != 1 and len(rows) != 1: raise ValueError("Cannot specify count and a table together.") for row in rows: for _ in range(count): factory(**row)
def count_users(self, nusers): """Test the number of users I have made""" nusers = guess_types(nusers) assert_equal(nusers, len(User.users))
def count_agencies(self, nagencies): """Test the number of agencies I have made""" nagencies = guess_types(nagencies) assert_equal(nagencies, len(Agency.agencies))