Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This file is part of a larger set of unit testing scripts that ensures an API works properly. The API that this file tests is mod_api uploaded here on my github account as a gist named __init__.py
- # tests/test_api.py
- import unittest
- from tests.base import BaseTestCase
- from app.models import db, User, Account, Location, Department, Room, Bracket, \
- ContainerType, Unit, ScanSet, Container
- from flask_security import current_user
- from flask import jsonify
- from sample_data import good_data
- import json
- from base64 import b64encode
- def create_container_data():
- nu = Unit.query.filter_by(description="Test Unit")
- if not Unit.query.all():
- nu = Unit("Test Unit")
- db.session.add(nu)
- db.session.commit()
- for x in range(12):
- ct = ContainerType(
- description = "Test Type %s" % (x),
- capacity = ((x+1)*10),
- unit = nu,
- avg_weight = (float((x+1)) *2.37))
- db.session.add(ct)
- db.session.commit()
- def create_a_company(company_name="Test Company"):
- new_account = Account()
- new_account.name = company_name
- new_account.contact = "Peter Griffin"
- new_account.phone_number = "(555) 555-0398"
- new_account.email = "peter_griffin@gmail.com"
- db.session.add(new_account)
- db.session.commit()
- return new_account
- def create_account_data(account, data_list):
- new_locations = []
- csv_file = data_list
- locations = list(set([row['location'] for row in csv_file]))
- for loc in locations:
- new_locations.append(Location(loc))
- loc_departments = list(set([row['department'] for row in csv_file if row['location'] == loc]))
- # print(loc_departments)
- map(new_locations[-1].departments.append, [Department(s) for s in loc_departments])
- # print(new_locations[-1])
- for dept in new_locations[-1].departments:
- dept_rooms = list(set([row['room'] for row in csv_file if row['location'] == loc and row['department'] == dept.name]))
- map(dept.rooms.append, [Room(r) for r in dept_rooms])
- for room in dept.rooms:
- brackets = [(row['container-type-id'],row['container-barcode']) for row in csv_file
- if row['location'] == loc and row['department'] == dept.name and row['room'] == room.number]
- map(room.brackets.append, [Bracket(b[1],b[0]) for b in brackets])
- for loc in new_locations:
- loc.account_id = account.id
- db.session.add(loc)
- db.session.commit()
- class TestApi(BaseTestCase):
- def login_user(self,email, password, context):
- response = context.post(
- '/login',
- data=dict(email=email, password=password),
- follow_redirects=True
- )
- def get_token(self, email, password, context):
- headers = {}
- headers['Authorization'] = 'Basic ' + b64encode((email + ':' + password).encode('utf-8')).decode('utf-8')
- headers['Content-Type'] = 'application/json'
- headers['Accept'] = 'application/json'
- response = context.get('/api/token', headers=headers)
- print(response.data)
- self.assertTrue(response.status_code == 200) # Returns 401 instead
- the_token = json.loads(str(response.data))
- the_token = the_token.get('token')
- return the_token
- def test_get_resources(self):
- the_test_company_name = "Dr. Nick Health Place"
- # Components
- with self.app.test_client() as c:
- user = User.query.filter_by(email="8arcena@gmail.com").first()
- new_company_account = create_a_company(the_test_company_name)
- user.account = new_company_account
- db.session.commit()
- create_container_data()
- create_account_data(user.account, good_data)
- # assert account data was created
- self.assertEqual(3, len(new_company_account.locations))
- loc = [loc for loc in new_company_account.locations if loc.name == "LOCATION A"]
- self.assertEqual(2, len(loc[0].departments))
- # get token
- the_token = self.get_token("8arcena@gmail.com", "admin123",c)
- ## GET BRACKETS by use of token
- response=self.client.get('/api/brackets?token='+the_token)
- resp = json.loads(str((response.data)))
- # assert 24 brackets for user's account
- self.assertEqual(18, len(resp['brackets']))
- self.assertEqual(the_test_company_name, resp['account']['name'])
- self.assertEqual("Test First Name", resp['user']['first_name'])
- self.assertEqual("Test Last Name", resp['user']['last_name'])
- # get container types
- response=self.client.get('/api/container-types?token='+the_token)
- resp = json.loads(str((response.data)))
- # assert 12 container types are retrieved by API
- self.assertEqual(12, len(resp))
- # A scan set looks like this:
- # {
- # "user_id" : 12,
- # "account_id ": 3,
- # "brackets": [
- # {"bracket_id":7, "date_scanned":"1487046586",
- # "scanned_containers": [1,4,3,5,3,2],
- # },
- # {"bracket_id":7, "date_scanned":"1487046586",
- # "scanned_containers": [1],
- # }
- # ]
- # }
- #
- # @unittest.skip("SKIPPING test_convert_to_orders")
- def test_post_scan_set(self):
- the_test_company_name = "Dr. Dixon's Hospital Account"
- # Components
- with self.app.test_client() as c:
- self.login_user("8arcena@gmail.com","admin123", c)
- self.assertTrue(current_user.id == 1)
- user = User.query.filter_by(email="8arcena@gmail.com").first()
- new_company_account = create_a_company(the_test_company_name)
- user.account = new_company_account
- db.session.commit()
- create_container_data()
- create_account_data(user.account, good_data)
- # assert account data was created
- self.assertEqual(3, len(new_company_account.locations))
- loc = [loc for loc in new_company_account.locations if loc.name == "LOCATION A"]
- self.assertEqual(2, len(loc[0].departments))
- # get token
- the_token = self.get_token("8arcena@gmail.com", "admin123", c)
- ## GET BRACKETS by use of token
- response=self.client.get('/api/brackets?token='+the_token)
- resp = json.loads(str((response.data)))
- import random
- import time
- scan_set = {
- "user_id" : user.id,
- "account_id" : new_company_account.id,
- "brackets" : []}
- # append scans
- # 5 brackets will be scanned/ replaced, 1 container will not be replaced
- print("resp['brackets']")
- for e in resp['brackets']:
- print('bracket_id = '+ str(e['id']))
- for c in e['containers']:
- print('container-id',c['id'])
- # print('container_type_id',c['container_type_id'])
- print('container-type',c['container_type'])
- for ridx in range(0,5):
- # set random container list index
- random.seed(10)
- min_max_containers = (0, len(resp['brackets'][ridx]['containers'])-1 )
- ridx_2 = random.randint(*min_max_containers)
- bracket_id = int(resp['brackets'][ridx][u'id'])
- scanned_containers = [int(resp['brackets'][ridx]['containers'][ridx_2]['id'])]
- date_scanned = int(time.time())
- # append the scan
- scan_set["brackets"].append({
- "bracket_id":bracket_id,
- "scanned_containers":scanned_containers,
- "date_scanned":date_scanned})
- # append set with no scanned container
- bracket_id = int(resp['brackets'][7]['id'])
- bracket_with_no_container_replacements = bracket_id
- scanned_containers = []
- date_scanned = int(time.time())
- scan_set["brackets"].append({
- "bracket_id":bracket_id,
- "scanned_containers":scanned_containers,
- "date_scanned":date_scanned})
- response = self.client.post('/api/scan?token='+the_token,
- data=json.dumps(scan_set),
- content_type='application/json')
- print("json.dumps(scan_set)")
- print(json.dumps(scan_set))
- self.assertIn("Scans Submitted", str(response.data))
- sets = ScanSet.query.all()
- print('\n'.join([str(s) for s in sets]))
- self.assertEqual(6,len(sets))
- with_no_scans = ScanSet.query.filter(
- ScanSet.bracket_id==bracket_with_no_container_replacements
- ).first()
- self.assertEqual(with_no_scans.scanned, [])
- # @unittest.skip("SKIPPING test_convert_to_orders")
- def test_404(self):
- # Ensure 404 error is handled.
- response = self.client.get('/404')
- self.assert404(response)
- self.assertTemplateUsed('errors/404.html')
- if __name__ == '__main__':
- unittest.main()
Add Comment
Please, Sign In to add comment