test_api
1import unittest 2from base import api, setup_mongo_client 3from unittest.mock import patch, Mock 4from flask import json 5 6class APITestCase(unittest.TestCase): 7 8 def setUp(self): 9 self.app = api 10 self.app.config['TESTING'] = True 11 setup_mongo_client(self.app) # Set up the mongo client after changing the TESTING flag 12 self.client = self.app.test_client() 13 print("Using MongoDB client:", type(self.app.mongo_client)) 14 15 16 def test_get_events(self): 17 # Create a mock collection 18 db = self.app.mongo_client['test'] 19 collection = db['events'] 20 21 # Replace the collection's find method with a Mock object 22 mock_find = Mock() 23 collection.find = mock_find 24 mock_find.return_value = [ 25 {"_id": "Event 1"}, 26 {"_id": "Event 2"}, 27 ] 28 29 response = self.client.get('/events') 30 self.assertEqual(response.status_code, 200) 31 32 33 @patch("pymongo.collection.Collection.update_one") 34 def test_register_success(self, mock_update_one): 35 app_client = api.test_client() # Create a test client for this test case 36 37 # Mock the update_one method to simulate a successful registration 38 mock_update_one.return_value = Mock(upserted_id=123) 39 40 test_data = { 41 'email': 'test_user', 42 'password': 'test_password', 43 'firstName': 'Test', 44 'lastName': 'User' 45 } 46 47 response = app_client.post('/register', json=test_data) 48 49 self.assertEqual(response.status_code, 200) 50 51 response_data = response.get_json() 52 self.assertEqual(response_data['msg'], "register successful") 53 54 def test_unauthorized_get_user_registered_events(self): 55 # Mock the database query result 56 app_client = api.test_client() 57 58 db = app_client.application.mongo_client['test'] # Access the app's Mongo client 59 collection = db['user'] 60 mock_find = Mock() 61 62 collection.find = mock_find 63 mock_find.return_value = [ 64 {"eventTitle": "Yoga"}, 65 {"eventTitle": "Swimming"} 66 ] 67 68 with patch("flask_jwt_extended.get_jwt_identity", return_value="test_user"): 69 response = app_client.get('/usersEvents') 70 71 self.assertEqual(response.status_code, 401) 72 73 74 @patch('base.request') 75 @patch('base.jwt_required') 76 @patch('base.mongo') 77 def test_unauthorized_enrolled_true(self, mock_mongo, mock_jwt_required, mock_request): 78 app_client = api.test_client() 79 # Mock request.json() method to return test data 80 mock_request.json.return_value = {'eventTitle': 'Event Name'} 81 82 # Mock get_jwt_identity() to return a test user identity 83 mock_jwt_required.return_value = lambda f: f 84 85 # Mock the find_one method to return an enrollment 86 mock_mongo.user.find_one.return_value = {'email': 'test@example.com', 'eventTitle': 'Event Name'} 87 88 response = app_client.post('/is-enrolled') 89 data = json.loads(response.get_data(as_text=True)) 90 91 self.assertEqual(response.status_code, 401) 92 93 @patch('base.get_jwt_identity') 94 @patch('base.mongo') 95 def test_my_profile_unauthorized(self, mock_mongo, mock_get_jwt_identity): 96 app_client = api.test_client() 97 # Mock get_jwt_identity() to return None, indicating an unauthorized user 98 mock_get_jwt_identity.return_value = None 99 100 response = app_client .get('/profile') 101 102 self.assertEqual(response.status_code, 401) 103 104 @patch('base.get_jwt_identity') 105 @patch('base.mongo') 106 def test_usersEvents_unauthorized(self, mock_mongo, mock_get_jwt_identity): 107 app_client = api.test_client() 108 # Mock get_jwt_identity() to return None, indicating an unauthorized user 109 mock_get_jwt_identity.return_value = None 110 111 response = app_client .get('/usersEvents') 112 113 self.assertEqual(response.status_code, 401) 114 115 @patch('base.get_jwt_identity') 116 @patch('base.mongo') 117 def test_foodCalorieMapping_unauthorized(self, mock_mongo, mock_get_jwt_identity): 118 app_client = api.test_client() 119 # Mock get_jwt_identity() to return None, indicating an unauthorized user 120 mock_get_jwt_identity.return_value = None 121 122 response = app_client .get('/foodCalorieMapping') 123 124 self.assertEqual(response.status_code, 401) 125 126 127 @patch('base.get_jwt_identity') 128 @patch('base.mongo') 129 def test_weekHistory_unauthorized(self, mock_mongo, mock_get_jwt_identity): 130 app_client = api.test_client() 131 # Mock get_jwt_identity() to return None, indicating an unauthorized user 132 mock_get_jwt_identity.return_value = None 133 134 response = app_client .get('/weekHistory') 135 136 self.assertEqual(response.status_code, 405) 137 138 @patch('base.get_jwt_identity') 139 @patch('base.mongo') 140 def test_caloriesBurned_unauthorized(self, mock_mongo, mock_get_jwt_identity): 141 app_client = api.test_client() 142 # Mock get_jwt_identity() to return None, indicating an unauthorized user 143 mock_get_jwt_identity.return_value = None 144 145 response = app_client .get('/caloriesBurned') 146 147 self.assertEqual(response.status_code, 405) 148 149 @patch('base.get_jwt_identity') 150 @patch('base.mongo') 151 def test_goalsUpdate_unauthorized(self, mock_mongo, mock_get_jwt_identity): 152 app_client = api.test_client() 153 # Mock get_jwt_identity() to return None, indicating an unauthorized user 154 mock_get_jwt_identity.return_value = None 155 156 response = app_client .get('/goalsUpdate') 157 158 self.assertEqual(response.status_code, 405) 159 160 @patch('base.get_jwt_identity') 161 @patch('base.mongo') 162 def test_profileUpdate_unauthorized(self, mock_mongo, mock_get_jwt_identity): 163 app_client = api.test_client() 164 # Mock get_jwt_identity() to return None, indicating an unauthorized user 165 mock_get_jwt_identity.return_value = None 166 167 response = app_client .get('/profileUpdate') 168 169 self.assertEqual(response.status_code, 405) 170 171 @patch('base.get_jwt_identity') 172 @patch('base.mongo') 173 def test_caloriesConsumed_unauthorized(self, mock_mongo, mock_get_jwt_identity): 174 app_client = api.test_client() 175 # Mock get_jwt_identity() to return None, indicating an unauthorized user 176 mock_get_jwt_identity.return_value = None 177 178 response = app_client .get('/caloriesConsumed') 179 180 self.assertEqual(response.status_code, 405) 181 182 @patch('base.get_jwt_identity') 183 @patch('base.mongo') 184 def test_createFood_success(self, mock_mongo, mock_update_one): 185 app_client = api.test_client() 186 187 mock_update_one.return_value = Mock(upserted_id=123) 188 189 test_data = { 190 'foodName': 'test_food', 191 'calories': 'test_value' 192 } 193 194 response = app_client .post('/createFood', json=test_data) 195 196 self.assertEqual(response.status_code, 200) 197 198 response_data = response.get_json() 199 self.assertEqual(response_data['status'], "Data saved successfully") 200 201 @patch('base.get_jwt_identity') 202 @patch('base.mongo') 203 def test_createMeal_unauthorized(self, mock_mongo, mock_get_jwt_identity): 204 app_client = api.test_client() 205 206 mock_get_jwt_identity.return_value = None 207 208 test_data = { 209 'mealName': 'test_meal', 210 'ingredients': ['test_ingredient_1', 'test_ingredient_2'] 211 } 212 213 response = app_client .post('/createMeal', json=test_data) 214 215 self.assertEqual(response.status_code, 401) 216 217 @patch('base.get_jwt_identity') 218 @patch('base.mongo') 219 def test_unenroll_unauthorized(self, mock_mongo, mock_get_jwt_identity): 220 app_client = api.test_client() 221 222 mock_get_jwt_identity.return_value = None 223 224 test_data = { 225 'eventTitle': 'test_title' 226 } 227 228 response = app_client .post('/unenroll', json=test_data) 229 230 self.assertEqual(response.status_code, 401) 231 232 @patch('base.get_jwt_identity') 233 @patch('base.mongo') 234 def test_myMeals_unauthorized(self, mock_mongo, mock_get_jwt_identity): 235 app_client = api.test_client() 236 237 mock_get_jwt_identity.return_value = None 238 239 response = app_client .get('/myMeals') 240 241 self.assertEqual(response.status_code, 401) 242 243if __name__ == "__main__": 244 unittest.main()
7class APITestCase(unittest.TestCase): 8 9 def setUp(self): 10 self.app = api 11 self.app.config['TESTING'] = True 12 setup_mongo_client(self.app) # Set up the mongo client after changing the TESTING flag 13 self.client = self.app.test_client() 14 print("Using MongoDB client:", type(self.app.mongo_client)) 15 16 17 def test_get_events(self): 18 # Create a mock collection 19 db = self.app.mongo_client['test'] 20 collection = db['events'] 21 22 # Replace the collection's find method with a Mock object 23 mock_find = Mock() 24 collection.find = mock_find 25 mock_find.return_value = [ 26 {"_id": "Event 1"}, 27 {"_id": "Event 2"}, 28 ] 29 30 response = self.client.get('/events') 31 self.assertEqual(response.status_code, 200) 32 33 34 @patch("pymongo.collection.Collection.update_one") 35 def test_register_success(self, mock_update_one): 36 app_client = api.test_client() # Create a test client for this test case 37 38 # Mock the update_one method to simulate a successful registration 39 mock_update_one.return_value = Mock(upserted_id=123) 40 41 test_data = { 42 'email': 'test_user', 43 'password': 'test_password', 44 'firstName': 'Test', 45 'lastName': 'User' 46 } 47 48 response = app_client.post('/register', json=test_data) 49 50 self.assertEqual(response.status_code, 200) 51 52 response_data = response.get_json() 53 self.assertEqual(response_data['msg'], "register successful") 54 55 def test_unauthorized_get_user_registered_events(self): 56 # Mock the database query result 57 app_client = api.test_client() 58 59 db = app_client.application.mongo_client['test'] # Access the app's Mongo client 60 collection = db['user'] 61 mock_find = Mock() 62 63 collection.find = mock_find 64 mock_find.return_value = [ 65 {"eventTitle": "Yoga"}, 66 {"eventTitle": "Swimming"} 67 ] 68 69 with patch("flask_jwt_extended.get_jwt_identity", return_value="test_user"): 70 response = app_client.get('/usersEvents') 71 72 self.assertEqual(response.status_code, 401) 73 74 75 @patch('base.request') 76 @patch('base.jwt_required') 77 @patch('base.mongo') 78 def test_unauthorized_enrolled_true(self, mock_mongo, mock_jwt_required, mock_request): 79 app_client = api.test_client() 80 # Mock request.json() method to return test data 81 mock_request.json.return_value = {'eventTitle': 'Event Name'} 82 83 # Mock get_jwt_identity() to return a test user identity 84 mock_jwt_required.return_value = lambda f: f 85 86 # Mock the find_one method to return an enrollment 87 mock_mongo.user.find_one.return_value = {'email': 'test@example.com', 'eventTitle': 'Event Name'} 88 89 response = app_client.post('/is-enrolled') 90 data = json.loads(response.get_data(as_text=True)) 91 92 self.assertEqual(response.status_code, 401) 93 94 @patch('base.get_jwt_identity') 95 @patch('base.mongo') 96 def test_my_profile_unauthorized(self, mock_mongo, mock_get_jwt_identity): 97 app_client = api.test_client() 98 # Mock get_jwt_identity() to return None, indicating an unauthorized user 99 mock_get_jwt_identity.return_value = None 100 101 response = app_client .get('/profile') 102 103 self.assertEqual(response.status_code, 401) 104 105 @patch('base.get_jwt_identity') 106 @patch('base.mongo') 107 def test_usersEvents_unauthorized(self, mock_mongo, mock_get_jwt_identity): 108 app_client = api.test_client() 109 # Mock get_jwt_identity() to return None, indicating an unauthorized user 110 mock_get_jwt_identity.return_value = None 111 112 response = app_client .get('/usersEvents') 113 114 self.assertEqual(response.status_code, 401) 115 116 @patch('base.get_jwt_identity') 117 @patch('base.mongo') 118 def test_foodCalorieMapping_unauthorized(self, mock_mongo, mock_get_jwt_identity): 119 app_client = api.test_client() 120 # Mock get_jwt_identity() to return None, indicating an unauthorized user 121 mock_get_jwt_identity.return_value = None 122 123 response = app_client .get('/foodCalorieMapping') 124 125 self.assertEqual(response.status_code, 401) 126 127 128 @patch('base.get_jwt_identity') 129 @patch('base.mongo') 130 def test_weekHistory_unauthorized(self, mock_mongo, mock_get_jwt_identity): 131 app_client = api.test_client() 132 # Mock get_jwt_identity() to return None, indicating an unauthorized user 133 mock_get_jwt_identity.return_value = None 134 135 response = app_client .get('/weekHistory') 136 137 self.assertEqual(response.status_code, 405) 138 139 @patch('base.get_jwt_identity') 140 @patch('base.mongo') 141 def test_caloriesBurned_unauthorized(self, mock_mongo, mock_get_jwt_identity): 142 app_client = api.test_client() 143 # Mock get_jwt_identity() to return None, indicating an unauthorized user 144 mock_get_jwt_identity.return_value = None 145 146 response = app_client .get('/caloriesBurned') 147 148 self.assertEqual(response.status_code, 405) 149 150 @patch('base.get_jwt_identity') 151 @patch('base.mongo') 152 def test_goalsUpdate_unauthorized(self, mock_mongo, mock_get_jwt_identity): 153 app_client = api.test_client() 154 # Mock get_jwt_identity() to return None, indicating an unauthorized user 155 mock_get_jwt_identity.return_value = None 156 157 response = app_client .get('/goalsUpdate') 158 159 self.assertEqual(response.status_code, 405) 160 161 @patch('base.get_jwt_identity') 162 @patch('base.mongo') 163 def test_profileUpdate_unauthorized(self, mock_mongo, mock_get_jwt_identity): 164 app_client = api.test_client() 165 # Mock get_jwt_identity() to return None, indicating an unauthorized user 166 mock_get_jwt_identity.return_value = None 167 168 response = app_client .get('/profileUpdate') 169 170 self.assertEqual(response.status_code, 405) 171 172 @patch('base.get_jwt_identity') 173 @patch('base.mongo') 174 def test_caloriesConsumed_unauthorized(self, mock_mongo, mock_get_jwt_identity): 175 app_client = api.test_client() 176 # Mock get_jwt_identity() to return None, indicating an unauthorized user 177 mock_get_jwt_identity.return_value = None 178 179 response = app_client .get('/caloriesConsumed') 180 181 self.assertEqual(response.status_code, 405) 182 183 @patch('base.get_jwt_identity') 184 @patch('base.mongo') 185 def test_createFood_success(self, mock_mongo, mock_update_one): 186 app_client = api.test_client() 187 188 mock_update_one.return_value = Mock(upserted_id=123) 189 190 test_data = { 191 'foodName': 'test_food', 192 'calories': 'test_value' 193 } 194 195 response = app_client .post('/createFood', json=test_data) 196 197 self.assertEqual(response.status_code, 200) 198 199 response_data = response.get_json() 200 self.assertEqual(response_data['status'], "Data saved successfully") 201 202 @patch('base.get_jwt_identity') 203 @patch('base.mongo') 204 def test_createMeal_unauthorized(self, mock_mongo, mock_get_jwt_identity): 205 app_client = api.test_client() 206 207 mock_get_jwt_identity.return_value = None 208 209 test_data = { 210 'mealName': 'test_meal', 211 'ingredients': ['test_ingredient_1', 'test_ingredient_2'] 212 } 213 214 response = app_client .post('/createMeal', json=test_data) 215 216 self.assertEqual(response.status_code, 401) 217 218 @patch('base.get_jwt_identity') 219 @patch('base.mongo') 220 def test_unenroll_unauthorized(self, mock_mongo, mock_get_jwt_identity): 221 app_client = api.test_client() 222 223 mock_get_jwt_identity.return_value = None 224 225 test_data = { 226 'eventTitle': 'test_title' 227 } 228 229 response = app_client .post('/unenroll', json=test_data) 230 231 self.assertEqual(response.status_code, 401) 232 233 @patch('base.get_jwt_identity') 234 @patch('base.mongo') 235 def test_myMeals_unauthorized(self, mock_mongo, mock_get_jwt_identity): 236 app_client = api.test_client() 237 238 mock_get_jwt_identity.return_value = None 239 240 response = app_client .get('/myMeals') 241 242 self.assertEqual(response.status_code, 401)
A class whose instances are single test cases.
By default, the test code itself should be placed in a method named 'runTest'.
If the fixture may be used for many test cases, create as many test methods as are needed. When instantiating such a TestCase subclass, specify in the constructor arguments the name of the test method that the instance is to execute.
Test authors should subclass TestCase for their own tests. Construction and deconstruction of the test's environment ('fixture') can be implemented by overriding the 'setUp' and 'tearDown' methods respectively.
If it is necessary to override the __init__ method, the base class __init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by parts of the framework in order to be run.
When subclassing TestCase, you can set these attributes:
- failureException: determines which exception will be raised when the instance's assertion methods fail; test methods raising this exception will be deemed to have 'failed' rather than 'errored'.
- longMessage: determines whether long messages (including repr of objects used in assert methods) will be printed on failure in addition to any explicit message passed.
- maxDiff: sets the maximum length of a diff in failure messages by assert methods using difflib. It is looked up as an instance attribute so can be configured by individual tests if required.
9 def setUp(self): 10 self.app = api 11 self.app.config['TESTING'] = True 12 setup_mongo_client(self.app) # Set up the mongo client after changing the TESTING flag 13 self.client = self.app.test_client() 14 print("Using MongoDB client:", type(self.app.mongo_client))
Hook method for setting up the test fixture before exercising it.
17 def test_get_events(self): 18 # Create a mock collection 19 db = self.app.mongo_client['test'] 20 collection = db['events'] 21 22 # Replace the collection's find method with a Mock object 23 mock_find = Mock() 24 collection.find = mock_find 25 mock_find.return_value = [ 26 {"_id": "Event 1"}, 27 {"_id": "Event 2"}, 28 ] 29 30 response = self.client.get('/events') 31 self.assertEqual(response.status_code, 200)
34 @patch("pymongo.collection.Collection.update_one") 35 def test_register_success(self, mock_update_one): 36 app_client = api.test_client() # Create a test client for this test case 37 38 # Mock the update_one method to simulate a successful registration 39 mock_update_one.return_value = Mock(upserted_id=123) 40 41 test_data = { 42 'email': 'test_user', 43 'password': 'test_password', 44 'firstName': 'Test', 45 'lastName': 'User' 46 } 47 48 response = app_client.post('/register', json=test_data) 49 50 self.assertEqual(response.status_code, 200) 51 52 response_data = response.get_json() 53 self.assertEqual(response_data['msg'], "register successful")
183 @patch('base.get_jwt_identity') 184 @patch('base.mongo') 185 def test_createFood_success(self, mock_mongo, mock_update_one): 186 app_client = api.test_client() 187 188 mock_update_one.return_value = Mock(upserted_id=123) 189 190 test_data = { 191 'foodName': 'test_food', 192 'calories': 'test_value' 193 } 194 195 response = app_client .post('/createFood', json=test_data) 196 197 self.assertEqual(response.status_code, 200) 198 199 response_data = response.get_json() 200 self.assertEqual(response_data['status'], "Data saved successfully")
Inherited Members
- unittest.case.TestCase
- TestCase
- failureException
- longMessage
- maxDiff
- addTypeEqualityFunc
- addCleanup
- enterContext
- addClassCleanup
- enterClassContext
- tearDown
- setUpClass
- tearDownClass
- countTestCases
- defaultTestResult
- shortDescription
- id
- subTest
- run
- doCleanups
- doClassCleanups
- debug
- skipTest
- fail
- assertFalse
- assertTrue
- assertRaises
- assertWarns
- assertLogs
- assertNoLogs
- assertEqual
- assertNotEqual
- assertAlmostEqual
- assertNotAlmostEqual
- assertSequenceEqual
- assertListEqual
- assertTupleEqual
- assertSetEqual
- assertIn
- assertNotIn
- assertIs
- assertIsNot
- assertDictEqual
- assertDictContainsSubset
- assertCountEqual
- assertMultiLineEqual
- assertLess
- assertLessEqual
- assertGreater
- assertGreaterEqual
- assertIsNone
- assertIsNotNone
- assertIsInstance
- assertNotIsInstance
- assertRaisesRegex
- assertWarnsRegex
- assertRegex
- assertNotRegex
- failUnlessRaises
- failIf
- assertRaisesRegexp
- assertRegexpMatches
- assertNotRegexpMatches
- failUnlessEqual
- assertEquals
- failIfEqual
- assertNotEquals
- failUnlessAlmostEqual
- assertAlmostEquals
- failIfAlmostEqual
- assertNotAlmostEquals
- failUnless
- assert_