Guest User

Untitled

a guest
Jun 19th, 2018
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.11 KB | None | 0 0
  1. # 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
  2.  
  3.  
  4. # tests/test_api.py
  5. import unittest
  6.  
  7. from tests.base import BaseTestCase
  8. from app.models import db, User, Account, Location, Department, Room, Bracket, \
  9. ContainerType, Unit, ScanSet, Container
  10. from flask_security import current_user
  11.  
  12. from flask import jsonify
  13. from sample_data import good_data
  14. import json
  15. from base64 import b64encode
  16.  
  17.  
  18. def create_container_data():
  19. nu = Unit.query.filter_by(description="Test Unit")
  20. if not Unit.query.all():
  21. nu = Unit("Test Unit")
  22. db.session.add(nu)
  23. db.session.commit()
  24. for x in range(12):
  25. ct = ContainerType(
  26. description = "Test Type %s" % (x),
  27. capacity = ((x+1)*10),
  28. unit = nu,
  29. avg_weight = (float((x+1)) *2.37))
  30. db.session.add(ct)
  31. db.session.commit()
  32.  
  33. def create_a_company(company_name="Test Company"):
  34. new_account = Account()
  35. new_account.name = company_name
  36. new_account.contact = "Peter Griffin"
  37. new_account.phone_number = "(555) 555-0398"
  38. new_account.email = "peter_griffin@gmail.com"
  39. db.session.add(new_account)
  40. db.session.commit()
  41. return new_account
  42.  
  43.  
  44. def create_account_data(account, data_list):
  45. new_locations = []
  46. csv_file = data_list
  47. locations = list(set([row['location'] for row in csv_file]))
  48. for loc in locations:
  49. new_locations.append(Location(loc))
  50. loc_departments = list(set([row['department'] for row in csv_file if row['location'] == loc]))
  51. # print(loc_departments)
  52. map(new_locations[-1].departments.append, [Department(s) for s in loc_departments])
  53. # print(new_locations[-1])
  54. for dept in new_locations[-1].departments:
  55. dept_rooms = list(set([row['room'] for row in csv_file if row['location'] == loc and row['department'] == dept.name]))
  56. map(dept.rooms.append, [Room(r) for r in dept_rooms])
  57. for room in dept.rooms:
  58. brackets = [(row['container-type-id'],row['container-barcode']) for row in csv_file
  59. if row['location'] == loc and row['department'] == dept.name and row['room'] == room.number]
  60. map(room.brackets.append, [Bracket(b[1],b[0]) for b in brackets])
  61. for loc in new_locations:
  62. loc.account_id = account.id
  63. db.session.add(loc)
  64. db.session.commit()
  65. class TestApi(BaseTestCase):
  66. def login_user(self,email, password, context):
  67. response = context.post(
  68. '/login',
  69. data=dict(email=email, password=password),
  70. follow_redirects=True
  71. )
  72. def get_token(self, email, password, context):
  73. headers = {}
  74. headers['Authorization'] = 'Basic ' + b64encode((email + ':' + password).encode('utf-8')).decode('utf-8')
  75. headers['Content-Type'] = 'application/json'
  76. headers['Accept'] = 'application/json'
  77. response = context.get('/api/token', headers=headers)
  78. print(response.data)
  79. self.assertTrue(response.status_code == 200) # Returns 401 instead
  80. the_token = json.loads(str(response.data))
  81. the_token = the_token.get('token')
  82. return the_token
  83. def test_get_resources(self):
  84. the_test_company_name = "Dr. Nick Health Place"
  85. # Components
  86. with self.app.test_client() as c:
  87. user = User.query.filter_by(email="8arcena@gmail.com").first()
  88. new_company_account = create_a_company(the_test_company_name)
  89. user.account = new_company_account
  90. db.session.commit()
  91. create_container_data()
  92. create_account_data(user.account, good_data)
  93. # assert account data was created
  94. self.assertEqual(3, len(new_company_account.locations))
  95. loc = [loc for loc in new_company_account.locations if loc.name == "LOCATION A"]
  96. self.assertEqual(2, len(loc[0].departments))
  97. # get token
  98. the_token = self.get_token("8arcena@gmail.com", "admin123",c)
  99. ## GET BRACKETS by use of token
  100. response=self.client.get('/api/brackets?token='+the_token)
  101. resp = json.loads(str((response.data)))
  102. # assert 24 brackets for user's account
  103. self.assertEqual(18, len(resp['brackets']))
  104. self.assertEqual(the_test_company_name, resp['account']['name'])
  105. self.assertEqual("Test First Name", resp['user']['first_name'])
  106. self.assertEqual("Test Last Name", resp['user']['last_name'])
  107. # get container types
  108. response=self.client.get('/api/container-types?token='+the_token)
  109. resp = json.loads(str((response.data)))
  110. # assert 12 container types are retrieved by API
  111. self.assertEqual(12, len(resp))
  112. # A scan set looks like this:
  113. # {
  114. # "user_id" : 12,
  115. # "account_id ": 3,
  116. # "brackets": [
  117. # {"bracket_id":7, "date_scanned":"1487046586",
  118. # "scanned_containers": [1,4,3,5,3,2],
  119. # },
  120. # {"bracket_id":7, "date_scanned":"1487046586",
  121. # "scanned_containers": [1],
  122. # }
  123. # ]
  124. # }
  125. #
  126. # @unittest.skip("SKIPPING test_convert_to_orders")
  127. def test_post_scan_set(self):
  128. the_test_company_name = "Dr. Dixon's Hospital Account"
  129. # Components
  130. with self.app.test_client() as c:
  131. self.login_user("8arcena@gmail.com","admin123", c)
  132. self.assertTrue(current_user.id == 1)
  133. user = User.query.filter_by(email="8arcena@gmail.com").first()
  134. new_company_account = create_a_company(the_test_company_name)
  135. user.account = new_company_account
  136. db.session.commit()
  137. create_container_data()
  138. create_account_data(user.account, good_data)
  139. # assert account data was created
  140. self.assertEqual(3, len(new_company_account.locations))
  141. loc = [loc for loc in new_company_account.locations if loc.name == "LOCATION A"]
  142. self.assertEqual(2, len(loc[0].departments))
  143. # get token
  144. the_token = self.get_token("8arcena@gmail.com", "admin123", c)
  145. ## GET BRACKETS by use of token
  146. response=self.client.get('/api/brackets?token='+the_token)
  147. resp = json.loads(str((response.data)))
  148. import random
  149. import time
  150. scan_set = {
  151. "user_id" : user.id,
  152. "account_id" : new_company_account.id,
  153. "brackets" : []}
  154. # append scans
  155. # 5 brackets will be scanned/ replaced, 1 container will not be replaced
  156. print("resp['brackets']")
  157. for e in resp['brackets']:
  158. print('bracket_id = '+ str(e['id']))
  159. for c in e['containers']:
  160. print('container-id',c['id'])
  161. # print('container_type_id',c['container_type_id'])
  162. print('container-type',c['container_type'])
  163. for ridx in range(0,5):
  164. # set random container list index
  165. random.seed(10)
  166. min_max_containers = (0, len(resp['brackets'][ridx]['containers'])-1 )
  167. ridx_2 = random.randint(*min_max_containers)
  168. bracket_id = int(resp['brackets'][ridx][u'id'])
  169. scanned_containers = [int(resp['brackets'][ridx]['containers'][ridx_2]['id'])]
  170. date_scanned = int(time.time())
  171. # append the scan
  172. scan_set["brackets"].append({
  173. "bracket_id":bracket_id,
  174. "scanned_containers":scanned_containers,
  175. "date_scanned":date_scanned})
  176. # append set with no scanned container
  177. bracket_id = int(resp['brackets'][7]['id'])
  178. bracket_with_no_container_replacements = bracket_id
  179. scanned_containers = []
  180. date_scanned = int(time.time())
  181. scan_set["brackets"].append({
  182. "bracket_id":bracket_id,
  183. "scanned_containers":scanned_containers,
  184. "date_scanned":date_scanned})
  185. response = self.client.post('/api/scan?token='+the_token,
  186. data=json.dumps(scan_set),
  187. content_type='application/json')
  188. print("json.dumps(scan_set)")
  189. print(json.dumps(scan_set))
  190. self.assertIn("Scans Submitted", str(response.data))
  191. sets = ScanSet.query.all()
  192. print('\n'.join([str(s) for s in sets]))
  193. self.assertEqual(6,len(sets))
  194. with_no_scans = ScanSet.query.filter(
  195. ScanSet.bracket_id==bracket_with_no_container_replacements
  196. ).first()
  197. self.assertEqual(with_no_scans.scanned, [])
  198. # @unittest.skip("SKIPPING test_convert_to_orders")
  199. def test_404(self):
  200. # Ensure 404 error is handled.
  201. response = self.client.get('/404')
  202. self.assert404(response)
  203. self.assertTemplateUsed('errors/404.html')
  204.  
  205.  
  206. if __name__ == '__main__':
  207. unittest.main()
Add Comment
Please, Sign In to add comment