def bucketlists(): """method for retrieving and creating bucket lists.""" access_token = request.headers.get("Authorization") if access_token: user_id = User.decode_token(access_token) if not isinstance(user_id, str): if request.method == 'POST': name = str(request.data.get('name', '')) u_id = user_id if name: bucketlist = Bucketlist(name=name, user_id=u_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name }) response.status_code = 201 return response else: bucket_lists = Bucketlist.get_all() results = [] for bucketlist in bucket_lists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, } results.append(obj) response = jsonify(results) response.status_code = 200 return response response = {"message": "Please login first."} response.status_code = 403 return jsonify(response)
def bucketlists(): if request.method == 'POST': name=str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.date_created, 'date_created': bucketlist.date_created, 'date_modiified': bucketlist.date_modified }) response.status_code = 201 return response else: bucketlists = Bucketlist.get_all() results = [] for bucketlist in bucketlists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified':bucketlist.date_modified } results.append(obj) response = jsonify(results) response.status_code = 200 return response
def bucketlists(): if request.method == "POST": name = str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified }) response.status_code = 201 return response else: # GET bucketlists = Bucketlist.get_all() results = [] for bucketlist in bucketlists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified } results.append(obj) response = jsonify(results) response.status_code = 200 return response
def setUp(self): # setup the app and push app context: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() # setup the db: db.drop_all() db.create_all() # create test datas for the users, bucketlists, and items: user = User( username='******', email='*****@*****.**', password='******' ) user.save() self.user = User(email="*****@*****.**", password="******", username="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.item = Item(name="Item 1", bucketlist_id=self.bucket_item.id) self.item.save() self.user2 = User(email="*****@*****.**", password="******", username="******") self.user2.save() self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id) self.bucket_item2.save() self.item2 = Item(name="Item 1", bucketlist_id=self.bucket_item2.id) self.item2.save() bucket_item = Bucketlist(name="Bucket List", user_id=user.id) bucket_item.save() item = Item(name="Item 1", bucketlist_id=bucket_item.id) item.save() self.client = self.app.test_client() #create default login login_details = { 'email': '*****@*****.**', 'password': '******'} response = self.client.post( url_for('api.login'), headers=self.get_api_headers(), data=json.dumps(login_details) ) self.token = json.loads(response.data)['token']
def setUp(self): from app.models import Bucketlist self.app = create_app(config_name='testing') self.client = self.app.test_client with self.app.app_context(): db.create_all() bucketlist = Bucketlist(name='Go to Delaware') bucketlist.save() self.bucketlist_id = bucketlist.id
def bucketlists(): # Get the access token from the header auth_header = request.headers.get('Authorization') access_token = auth_header.split(" ")[1] if access_token: # Attempt to decode the token and get the User ID user_id = User.decode_token(access_token) if not isinstance(user_id, str): # Go ahead and handle the request, the user is authenticated if request.method == "POST": bucket_name = str(request.data.get('bucket_name', '')) belongs_to = int() if not bucket_name: return { "message": "Please add a goal to your bucketlist" }, 404 if bucket_name: bucketlist = Bucketlist(bucket_name=bucket_name) bucketlist.belongs_to = user_id bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'bucket_name': bucketlist.bucket_name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'belongs_to': user_id }) return make_response(response), 201 else: # GET all buckets bucketlists = Bucketlist.query.filter_by(belongs_to=user_id) results = [] for bucketlist in bucketlists: obj = { 'id': bucketlist.id, 'bucket_name': bucketlist.bucket_name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'belongs_to': bucketlist.belongs_to } results.append(obj) return make_response(jsonify(results)), 200 else: # user is not legit, so the payload is an error message message = user_id response = { 'message': message } return make_response(jsonify(response)), 401
def create_bucketlists(): name = str(request.data.get("name","")) bucketlist = Bucketlist(name=name) bucketlist.save() response = jsonify({ "id": bucketlist.id, "name": bucketlist.name, "date_created": bucketlist.date_created, "date_modified": bucketlist.date_modified }) response.status_code = 201 return response
def bucketlists_post(): ''' Function for adding a users new bucketlist ''' auth_header = request.headers.get('Authorization') access_token = auth_header if access_token: user_id = User.decode_token(access_token) if not isinstance(user_id, str): user = User.query.filter_by(id=user_id).first() user_buckelists_list = [] user_buckelists = Bucketlist.query.filter_by( user_id=user_id).all() for user_buckelist in user_buckelists: user_buckelists_list.append(user_buckelist) user_bucketlist_id = len(user_buckelists_list) + 1 if request.method == "POST": name = str(request.data.get('name', '')) if name: items = Bucketlist.query.filter_by( user_id=user_id).all() items_list = [] for item in items: items_list.append(item.name) if name in items_list: response = jsonify( {'message': 'The bucketlist already exists'}) response.status_code = 400 return response else: bucketlist = Bucketlist( bucketlist_id=user_bucketlist_id, name=name, user_id=user.id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'bucketlist id': bucketlist.bucketlist_id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, }) response.status_code = 201 return response else: response = jsonify({'message': 'Invalid token'}) response.status_code = 401 return response
def bucketlists(): # Get the access token from the header auth_header = request.headers.get('Authorization') print("Auth header is ",auth_header) access_token = auth_header.split(" ")[1] if access_token: # Attempt to decode the token and get the User ID user_id = User.decode_token(access_token) print("user id is ",user_id) if not isinstance(user_id, str): # Go ahead and handle the request, the user is authenticated if request.method == "POST": content=request.json name=content["name"] # name = str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name, created_by=user_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id }) return make_response(response), 201 else: # GET all the bucketlists created by this user bucketlists = Bucketlist.query.filter_by(created_by=user_id) results = [] for bucketlist in bucketlists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': bucketlist.created_by } results.append(obj) return make_response(jsonify(results)), 200 else: # user is not legit, so the payload is an error message message = user_id response = { 'message': message } return make_response(jsonify(response)), 401
def bucketlists(): name = str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified }) response.status_code = 201 return response
class ModelTestCase(TestCase): """Defines the test suites for the bucket list model.""" def setUp(self): """ test client and other test variables.""" user = User.objects.create(username="******") self.name = "Write world class code" self.bucketlist = Bucketlist(name=self.name, owner=user) def test_model_can_create_a_bucketlist(self): """ Test bucketlist model can create a bucktlist.""" old_count = Bucketlist.objects.count() self.bucketlist.save() new_count = Bucketlist.objects.count() self.assertNotEqual(old_count,new_count)
def setUp(self): # setup the app and push app context: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() # setup the db: db.drop_all() db.create_all() # create test datas: user = User( username='******', email='*****@*****.**', password='******' ) user.save() self.user = User(email="*****@*****.**", password="******", username="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.user2 = User(email="*****@*****.**", password="******", username="******") self.user2.save() self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id) self.bucket_item2.save() bucket_item = Bucketlist(name="Bucket List", user_id=user.id) bucket_item.save() self.client = self.app.test_client() #default login details login_details = { 'email': '*****@*****.**', 'password': '******'} response = self.client.post( url_for('api.login'), headers=self.get_api_headers(), data=json.dumps(login_details) ) self.token = json.loads(response.data)['token']
def bucketlists(): # get the access token auth_header = request.headers.get('Authorization') access_token = auth_header.split(" ")[1] if access_token: user_id = User.decode_token(access_token) if not isinstance(user_id, str): # Go ahead and handle the request, the user is authed if request.method == "POST": name = str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name, created_by=user_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id }) return make_response(response), 201 else: # GET # get all the bucketlists for this user bucketlists = Bucketlist.get_all(user_id) results = [] for bucketlist in bucketlists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': bucketlist.created_by } results.append(obj) return make_response(jsonify(results)), 200 else: # user is not legit, so the payload is an error message message = user_id response = {'message': message} return make_response(jsonify(response)), 401
def create_bucketlist(user): """create bucketlist --- tags: - "bucketlists" parameters: - in: "header" name: "Authorization" description: "Token of logged in user" required: true type: string - in: "body" name: "body" description: "Name and description of bucketlist" schema: type: "object" required: - name - description properties: name: type: "string" description: type: "string" responses: 400: description: "Failed" 201: description: "Success" """ name = request.data['name'] description = request.data['description'] owner = user['user_id'] try: new_bucketlist = Bucketlist(name, description, owner) new_bucketlist.save() response = new_bucketlist.to_json() return make_response(jsonify(response)), 201 except Exception as e: response = {'status': 'Failed', 'message': str(e)} return make_response(jsonify(response)), 400
def bucket(): access_token = request.headers.get('Authorization') if access_token: user_id = User.decode_token(access_token) if isinstance(user_id, int): if request.method == "POST": data = request.get_json(force=True) name = data['name'] if name: bucketlist = Bucketlist(name=name, created_by=user_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id }) return make_response(response), 201 else: bucketlists = Bucketlist.query.filter_by(created_by=user_id) results = [] for bucketlist in bucketlists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': bucketlist.created_by } results.append(obj) return make_response(jsonify(results)), 200 else: message = user_id response = {'message': message} return make_response(jsonify(response)), 401
def post(self): """POST request handling for /bucketlists/ Create a new bucketlist for the user """ name = str(request.data.get('name', '')) date = str(request.data.get('date', '')) description = str(request.data.get('description', '')) if name: bucketlist = Bucketlist(user_id, name, date, description) bucketlist.save() response = jsonify({ 'user': bucketlist.user_id, 'id': bucketlist.id, 'name': bucketlist.bucketlist_name, 'date': bucketlist.deadline_date, 'description': bucketlist.bucketlist_description }) response.headers['Access-Control-Allow-Origin'] = "*" response.headers['Access-Control-Allow-Credentials'] = True response.headers[ 'Access-Control-Allow-Headers'] = 'Content-Type, Authorization' response.headers['Access-Control-Allow-Methods'] = 'POST' response.status_code = 201 return response
def bucketlists(): #check the type of request it receives if request.method == "POST": #CREATE BUCKETLIST OBJECT BY EXTRACTING NAME FROM THE REQUEST name=str(request.data.get('name','')) if name: bucketlist=Bucketlist(name=name) #save the created bucketlist bucketlist.save() response= jsonify({ 'id':bucketlist.id, 'name':bucketlist.name, 'date_created':bucketlist.date_created, 'date_modified':bucketlist.date_modified }) response.status_code= 201 return response #if request method is get else: bucketlists=Bucketlist.get_all()#this returns a list results=[] #iterate over the list of bucketlists for bucketlist in bucketlists: obj={ 'id':bucketlist.id, 'name':bucketlist.name, 'date_created':bucketlist.date_created, 'date_modified':bucketlist.date_modified } results.append(obj) response=jsonify(results) response.status_code=200 return response
class ModelTestCase(unittest.TestCase): """Test cases for the models """ def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.user = User(email="*****@*****.**", password="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.item = Item(name="Needs of bucket items", bucketlist_id=self.bucket_item.id) self.item.save() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_for_data_exsitence(self): """Test to check if the data were created""" bucketlist = Bucketlist.query.all() self.assertEqual(len(bucketlist),1) def test_for_data_delete(self): """ Test for the delete feature""" self.bucket_item.delete() bucketlist = Bucketlist.query.all() self.assertNotEqual(len(bucketlist),1) def test_for_edit_feature(self): """ test for edit feature """ self.item.edit("My Test Item") self.item.save() self.bucket_item.edit("My Test Item") self.bucket_item.save() self.assertEqual(self.bucket_item.name, "My Test Item") self.assertEqual(self.item.name, "My Test Item") def test_password_setter(self): """Test for password setter""" u = User(password='******') self.assertTrue(u.password_hash is not None) def test_no_password_getter(self): """ Test for password raises error""" u = User(password='******') with self.assertRaises(AttributeError): u.password def test_password_salts_are_random(self): """Test password salts are random""" u = User(password='******') u2 = User(password='******') self.assertTrue(u.password_hash != u2.password_hash) def test_user_str(self): """ Test string function of user """ user = str(self.user) self.assertIsNotNone(user) def test_for_to_json(self): """ Test to user_json """ #user to json user_json = self.user.to_json() #bucket-json to json bucket_json = self.bucket_item.to_json() #itme json to json item_json = self.item.to_json() self.assertIsNotNone(item_json) self.assertIsNotNone(bucket_json) self.assertIsNotNone(user_json)
def bucketlists(): # Get the access token from the passed header auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split("Bearer ")[1] if access_token: # Decode the token to get the user id user_id = User.decode_token(access_token) if not isinstance(user_id, str): if request.method == 'POST': try: title = request.json.get('title') if Bucketlist.title_exists(title): return jsonify({ "message": "A bucketlist with that name already exists. Please use a different name" }), 417 bucketlist = Bucketlist(title=title, created_by=user_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'title': bucketlist.title, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id, 'message': "Yaaay! Bucketlist successfully created" }) response.status_code = 201 return response except AttributeError: return jsonify({ "message": "The title cannot be blank" }), 417 else: # If GET q = request.args.get('q', ' ').strip() if q: items = Bucketlist.query.filter(Bucketlist.title.like("%"+q+"%"))\ .filter(Bucketlist.created_by==user_id).all() if items: results = [] for item in items: single = { 'id': item.id, 'title': item.title, 'date_created': item.date_created, 'date_modified': item.date_modified, 'created_by': user_id } results.append(single) response = jsonify(results), 200 if not results: return jsonify({ "message": "Hey, you don't have bucketlist yet, please create one" }), 404 return response if not items: return jsonify({"message": "Bucketlist not found"}) else: # Implement pagination # Get the pages parameter or set it to 1 raw_page = request.args.get('page') if raw_page: try: page = int(raw_page) except ValueError: return jsonify({"message": "The page must be an integer"}) else: page = 1 # default page # Set the limit of the no of bucketlists to be viewed raw_limit = request.args.get('limit') if raw_limit: try: limit = int(raw_limit) except ValueError: return jsonify({"message": "The limit must be an integer"}) else: limit = 10 # default limit # If q has not been passed / no search query made bucketlists = Bucketlist.get_all(user_id).paginate(page, limit, False) results = [] # if not results: # return jsonify({ # "message": "Hey, you don't have any bucketlist yet, please create one" # }), 404 if bucketlists.has_next: next_page_url = "?page=" + str(page + 1) + "&limit=" + str(limit) else: next_page_url = "" if bucketlists.has_prev: prev_page_url = "?page=" + str(page - 1) + "&limit=" + str(limit) else: prev_page_url = "" for bucketlist in bucketlists.items: item = { 'id': bucketlist.id, 'title': bucketlist.title, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id } results.append(item) response = jsonify({ 'next_url': next_page_url, 'prev_url': prev_page_url, 'results': results}), 200 return response else: # User_id not found, payload is an error msg return jsonify({ "message": "Error, could not authenticate. Please login first" }), 401 else: # No access token return jsonify({ "message": "Error, access token not found, you need to login first" }), 401 else: # No auth_header return jsonify({ "message": "Error, header access token not found, you need to login first" }), 401
class BucketlistTestCase(unittest.TestCase): """Test for bucket list route""" def setUp(self): # setup the app and push app context: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() # setup the db: db.drop_all() db.create_all() # create test datas: user = User( username='******', email='*****@*****.**', password='******' ) user.save() self.user = User(email="*****@*****.**", password="******", username="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.user2 = User(email="*****@*****.**", password="******", username="******") self.user2.save() self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id) self.bucket_item2.save() bucket_item = Bucketlist(name="Bucket List", user_id=user.id) bucket_item.save() self.client = self.app.test_client() #default login details login_details = { 'email': '*****@*****.**', 'password': '******'} response = self.client.post( url_for('api.login'), headers=self.get_api_headers(), data=json.dumps(login_details) ) self.token = json.loads(response.data)['token'] def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def get_api_headers(self, token=''): """Set default authorization headers for token""" return { 'Authorization': 'Basic ' + base64.b64encode( (token + ':' + '').encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_for_bad_request(self): """Test for bad request """ new_bucket_item = { "bucketlist_name": "New Bucketlist" } response = self.client.post(url_for('api.bucketlists'),headers=self.get_api_headers(self.token), data=new_bucket_item ) self.assertEqual(response.status_code,400) def test_for_new_bucketlist_item(self): """Test for addition of new bucketlist collection""" new_bucket_item = { "bucketlist_name": "New Bucketlist" } response = self.client.post(url_for('api.bucketlists'),headers=self.get_api_headers(self.token), data=json.dumps(new_bucket_item) ) self.assertEqual(response.status_code,201) def test_for_method_not_allowed(self): """Test for method not allowed exception""" response = self.client.put(url_for('api.bucketlists'),headers=self.get_api_headers()) self.assertEqual(response.status_code,405) def test_for_protected_url(self): """Test guest cant access protected url""" response = self.client.get(url_for('api.bucketlists'),headers=self.get_api_headers()) self.assertEqual(response.status_code,401) def test_for_internal_server_error(self): """Test guest cant access protected url""" response = self.client.get(url_for('api.bucketlists'),headers=self.get_api_headers()) self.assertEqual(response.status_code,401) def test_for_not_authorized(self): """Test for bucketlist can only be accessed by the owner""" #for /api/v1/:id/ response = self.client.get(url_for('api.manage_bucketlist', id=1),headers=self.get_api_headers(self.token)) #for /api/v1/:id/items response2 = self.client.get(url_for('api.bucketlist_items', id=1),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,401) self.assertEqual(response2.status_code,401) def test_get_bucketlist_authorized(self): """Test for authorized users can access bucket list""" response = self.client.get(url_for('api.manage_bucketlist', id=3),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,200) def test_get_bucketlist_item_authorized(self): """Test for authorized users can access bucket list""" response = self.client.get(url_for('api.bucketlist_items',id=3),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,200) def test_get_bucketlist_add_new_item_authorized(self): """Test for can add new item in the bucketlist """ new_item = { "item name": "New Item Bucketlist" } response = self.client.post(url_for('api.bucketlist_items', id=3),headers=self.get_api_headers(self.token), data=json.dumps(new_item)) self.assertEqual(response.status_code,201) def test_get_bucketlist_no_bucket_list(self): """Test for bucketlist collection doesn't exist""" response = self.client.get(url_for('api.bucketlist_items', id=5),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,404) def test_get_edit_bucketlist(self): """ Test for edit bucketlist collection""" edit_bucket_item = { "bucketlist_name": "Edited Bucketlist" } response = self.client.put(url_for('api.manage_bucketlist', id=3),headers=self.get_api_headers(self.token), data=json.dumps(edit_bucket_item) ) response_data = json.loads(response.data) self.assertEqual(response.status_code,201) def test_delete_bucketlist(self): """ Test for delete bucket list""" response = self.client.delete(url_for('api.manage_bucketlist', id=3),headers=self.get_api_headers(self.token) ) self.assertEqual(response.status_code,204) def test_for_bucket_list_item_not_found(self): """ test for get bucketlist item route /api/v1/:id/items not found """ response = self.client.get(url_for('api.manage_bucketlist', id=5),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,404) def test_for_url_not_found(self): """ test for none existing url within the api applicaito """ response = self.client.get(url_for('api.bucketlists') + '/custompage', headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,404)
def bucketlists(): # Get the access token from the header auth_header = request.headers.get('Authorization') access_token = auth_header.split(" ")[1] # import pdb # pdb.set_trace() if access_token: # Attempt to decode the token and get the User ID user_id = User.decode_token(access_token) # implement pagination limit = int(request.args.get("limit", 20)) page = int(request.args.get("page", 1)) if int(limit) > 100: limit = 10 search = request.args.get('q', None) if search: bucketlists = Bucketlist.query.filter( Bucketlist.name.ilike('%' + search + '%')).filter_by(user_id=user_id) if not Bucketlist.query.count(): return { "message": "No bucketlists found matching '{}'".format(search) } # print('user_id {!r}'.format(user_id)) # print('access_token: ', access_token) if isinstance(user_id, str): # Go ahead and handle the request, the user is authenticated if request.method == "POST": name = str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name, created_by=user_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id }) return make_response(response), 201 else: # GET all the bucketlists created by this user bucketlists = Bucketlist.query.filter_by( created_by=user_id) bucketlists = Bucketlist.query.paginate(page=page, per_page=limit, error_out=False) results = [] for bucketlist in bucketlists.items: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': bucketlist.created_by } results.append(obj) return make_response(jsonify(results)), 200 else: # user is not legit, so the payload is an error message message = "Anauthorized user" response = {'message': message} return make_response(jsonify(response)), 401
class BucketlistTestCase(unittest.TestCase): """" Test cases for the route /api/v1/:id/item/:item_id""" def setUp(self): # setup the app and push app context: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() # setup the db: db.drop_all() db.create_all() # create test datas for the users, bucketlists, and items: user = User( username='******', email='*****@*****.**', password='******' ) user.save() self.user = User(email="*****@*****.**", password="******", username="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.item = Item(name="Item 1", bucketlist_id=self.bucket_item.id) self.item.save() self.user2 = User(email="*****@*****.**", password="******", username="******") self.user2.save() self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id) self.bucket_item2.save() self.item2 = Item(name="Item 1", bucketlist_id=self.bucket_item2.id) self.item2.save() bucket_item = Bucketlist(name="Bucket List", user_id=user.id) bucket_item.save() item = Item(name="Item 1", bucketlist_id=bucket_item.id) item.save() self.client = self.app.test_client() #create default login login_details = { 'email': '*****@*****.**', 'password': '******'} response = self.client.post( url_for('api.login'), headers=self.get_api_headers(), data=json.dumps(login_details) ) self.token = json.loads(response.data)['token'] def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def get_api_headers(self, token='',): """ get authorization header with login credentials or token""" return { 'Authorization': 'Basic ' + base64.b64encode( (token + ':' + '').encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_for_error_bucketlist_or_item(self): """ test exception on the bucketlist item""" #response for not found bucketlists or item response = self.client.get(url_for('api.bucketlist_item', id=5, item_id=5),headers=self.get_api_headers(self.token)) #response for item not belonging to a bucketlist response_two= self.client.get(url_for('api.bucketlist_item', id=3, item_id=1),headers=self.get_api_headers(self.token)) #repsone for user not authorized for the bucketlist colleciton response_three = self.client.get(url_for('api.bucketlist_item', id=2, item_id=2),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,404) self.assertEqual(response_two.status_code,403) self.assertEqual(response_three.status_code,401) def test_for_each_authenticated_method(self): """Test for the http verbs for route /api/v1/:id/item/:item_id action""" item = { "item_name": "changed item" } #response for get request response = self.client.get(url_for('api.bucketlist_item', id=3, item_id=3),headers=self.get_api_headers(self.token)) #response for the put request response_two = self.client.put(url_for('api.bucketlist_item', id=3, item_id=3),headers=self.get_api_headers(self.token), data=json.dumps(item)) #response for delete request response_three= self.client.delete(url_for('api.bucketlist_item', id=3, item_id=3),headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code,200) self.assertEqual(response_two.status_code,201) self.assertEqual(response_three.status_code,204)
def bucketlists(): if request.method == 'POST': name = str(request.data.get('name', '')) if name: bucketlist = Bucketlist(name=name) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified }) response.status_code = 201 return response else: # GET bucketlists = Bucketlist.get_all() results = {} for bucklist in bucketlists: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified } results.apppend(obj) response = jsonify(results) response.status_code = 200 return response @app.route('/bucketlists/<int:id>', methods=['GET','PUT','DELETE']) def bucketlist_manipulation(id, **kwargs): # Retrieve bucketlists using ID bucketlist = Bucketlist.query.filter_by(id=id).first() if not bucketlist: # Raise an HTTPExeption with a 404 not found status code abort(404) if request.method == 'DELETE': bucketlist.delete() return { "message": "bucketlist {} deleted successfully".format(bucketlist.id) }, 200 elif request.method == 'PUT': name = str(request.data.get('name', '')) bucketlist.name = name bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'data_created': bucketlist.date_created, 'data_modified': bucketlist.date_modified }) response_status_code = 200 return response else: # GET response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'data_created': bucketlist.date_created, 'data_modified': bucketlist.date_modified }) response.status_code = 200 return response return app
class ModelTestCase(unittest.TestCase): """Test cases for the models """ def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.user = User(email="*****@*****.**", password="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.item = Item(name="Needs of bucket items", bucketlist_id=self.bucket_item.id) self.item.save() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_for_data_exsitence(self): """Test to check if the data were created""" bucketlist = Bucketlist.query.all() self.assertEqual(len(bucketlist), 1) def test_for_data_delete(self): """ Test for the delete feature""" self.bucket_item.delete() bucketlist = Bucketlist.query.all() self.assertNotEqual(len(bucketlist), 1) def test_for_edit_feature(self): """ test for edit feature """ self.item.edit("My Test Item") self.item.save() self.bucket_item.edit("My Test Item") self.bucket_item.save() self.assertEqual(self.bucket_item.name, "My Test Item") self.assertEqual(self.item.name, "My Test Item") def test_password_setter(self): """Test for password setter""" u = User(password='******') self.assertTrue(u.password_hash is not None) def test_no_password_getter(self): """ Test for password raises error""" u = User(password='******') with self.assertRaises(AttributeError): u.password def test_password_salts_are_random(self): """Test password salts are random""" u = User(password='******') u2 = User(password='******') self.assertTrue(u.password_hash != u2.password_hash) def test_user_str(self): """ Test string function of user """ user = str(self.user) self.assertIsNotNone(user) def test_for_to_json(self): """ Test to user_json """ #user to json user_json = self.user.to_json() #bucket-json to json bucket_json = self.bucket_item.to_json() #itme json to json item_json = self.item.to_json() self.assertIsNotNone(item_json) self.assertIsNotNone(bucket_json) self.assertIsNotNone(user_json)
def bucketlists(): """ Method to add a bucketlist or retrieve all bucketlists :return: response """ # check if the header with key is present if 'Authorization' not in request.headers: # Return a message to the user telling them that they need to submit an authorization header with token response = {'message': 'Header with key Authorization missing.'} return make_response(jsonify(response)), 401 else: # Get the access token from the header auth_header = request.headers.get('Authorization') # check for when authorization was not provided in header if not auth_header: # Return a message to the user telling them that they need to submit an authorization header with token response = { 'message': 'Token not provided in the header with key Authorization.' } return make_response(jsonify(response)), 401 else: auth_strings = auth_header.split(" ") if len(auth_strings) != 2: response = {'message': 'Invalid token format.'} return make_response(jsonify(response)), 401 else: access_token = auth_header.split(" ")[1] if access_token: # Attempt to decode the token and get the User ID user_id = User.decode_token(access_token) if not isinstance(user_id, str): # Go ahead and handle the request, the user is authenticated if request.method == "POST": if 'name' not in request.data: # Return a message to the user telling them that they need to submit a name response = { 'message': 'Parameter name missing.' } return make_response(jsonify(response)), 400 else: name = str(request.data.get('name', '')) if name: # query whether a bucketlist with the same name already exists bucketlists = Bucketlist.query.filter_by( created_by=user_id, name=name).first() if bucketlists: # Return a message to the user telling them that they need to submit a name response = { 'message': 'Bucketlist with this name already exists. ' 'Edit it or choose another name.' } return make_response( jsonify(response)), 409 else: bucketlist = Bucketlist( name=name, created_by=user_id) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'created_by': user_id }) return make_response(response), 201 else: # Return a message to the user telling them that they need to submit a name response = { 'message': 'Bucketlist name should not be empty.' } return make_response( jsonify(response)), 400 else: # get the query string for limit if it exists and for pagination # if the query parameter for limit doesn't exist, 20 is used by default limit = request.args.get( 'limit', 'default ' + str(Config.DEFAULT_PAGINATION_LIMIT)) try: limit = int(limit) except ValueError: # if limit value is gibberish, default to 20 limit = Config.DEFAULT_PAGINATION_LIMIT # if limit supplied is greater than 100, display only 100 if limit > Config.MAXIMUM_PAGINATION_LIMIT: limit = Config.MAXIMUM_PAGINATION_LIMIT # set the default page to display to 1 page = request.args.get('page', 'default 1') try: page = int(page) except ValueError: # if page value is gibberish, default to 1 page = 1 if limit < 1 or page < 1: return abort( 404, 'Page or Limit must be greater than 1') # get the query string for q - this is searching based on name search_string = request.args.get('q') # check if a search parameter was provided if search_string: # get bucketlists whose name contains the search string bucketlists = Bucketlist.query.filter_by( created_by=user_id).filter( Bucketlist.name.like('%' + search_string + '%')).paginate( page, limit) else: # GET all the bucketlists created by this user bucketlists = Bucketlist.query.filter_by( created_by=user_id).paginate(page, limit) results = [] if page == 1: prev_page = url_for( '.bucketlists') + '?limit={}'.format(limit) else: prev_page = url_for( '.bucketlists' ) + '?limit={}&page={}'.format( limit, page - 1) if page < bucketlists.pages: next_page = url_for( '.bucketlists' ) + '?limit={}&page={}'.format( limit, page + 1) else: next_page = None for bucketlist in bucketlists.items: obj = { 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified, 'items': [{ 'id': item.id, 'name': item.name, 'date_created': item.date_created, 'date_modified': item.date_modified, 'done': item.done } for item in bucketlist.bucketlist_items], 'created_by': bucketlist.created_by } results.append(obj) return make_response( jsonify({ 'page': page, 'items_per_page': limit, 'total_items': bucketlists.total, 'total_pages': bucketlists.pages, 'prev_page': prev_page, 'next_page': next_page, 'items': results })), 200 else: # user is not legit, so the payload is an error message message = user_id response = {'message': message} return make_response(jsonify(response)), 401 else: response = {'message': 'Empty token string'} return make_response(jsonify(response)), 401
class BucketlistTestCase(unittest.TestCase): """Test for bucket list route""" def setUp(self): # setup the app and push app context: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() # setup the db: db.drop_all() db.create_all() # create test datas: user = User(username='******', email='*****@*****.**', password='******') user.save() self.user = User(email="*****@*****.**", password="******", username="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.user2 = User(email="*****@*****.**", password="******", username="******") self.user2.save() self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id) self.bucket_item2.save() bucket_item = Bucketlist(name="Bucket List", user_id=user.id) bucket_item.save() self.client = self.app.test_client() #default login details login_details = { 'email': '*****@*****.**', 'password': '******' } response = self.client.post(url_for('api.login'), headers=self.get_api_headers(), data=json.dumps(login_details)) self.token = json.loads(response.data)['token'] def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def get_api_headers(self, token=''): """Set default authorization headers for token""" return { 'Authorization': 'Basic ' + base64.b64encode( (token + ':' + '').encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_for_bad_request(self): """Test for bad request """ new_bucket_item = {"bucketlist_name": "New Bucketlist"} response = self.client.post(url_for('api.bucketlists'), headers=self.get_api_headers(self.token), data=new_bucket_item) self.assertEqual(response.status_code, 400) def test_for_new_bucketlist_item(self): """Test for addition of new bucketlist collection""" new_bucket_item = {"bucketlist_name": "New Bucketlist"} response = self.client.post(url_for('api.bucketlists'), headers=self.get_api_headers(self.token), data=json.dumps(new_bucket_item)) self.assertEqual(response.status_code, 201) def test_for_method_not_allowed(self): """Test for method not allowed exception""" response = self.client.put(url_for('api.bucketlists'), headers=self.get_api_headers()) self.assertEqual(response.status_code, 405) def test_for_protected_url(self): """Test guest cant access protected url""" response = self.client.get(url_for('api.bucketlists'), headers=self.get_api_headers()) self.assertEqual(response.status_code, 401) def test_for_internal_server_error(self): """Test guest cant access protected url""" response = self.client.get(url_for('api.bucketlists'), headers=self.get_api_headers()) self.assertEqual(response.status_code, 401) def test_for_not_authorized(self): """Test for bucketlist can only be accessed by the owner""" #for /api/v1/:id/ response = self.client.get(url_for('api.manage_bucketlist', id=1), headers=self.get_api_headers(self.token)) #for /api/v1/:id/items response2 = self.client.get(url_for('api.bucketlist_items', id=1), headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 401) self.assertEqual(response2.status_code, 401) def test_get_bucketlist_authorized(self): """Test for authorized users can access bucket list""" response = self.client.get(url_for('api.manage_bucketlist', id=3), headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 200) def test_get_bucketlist_item_authorized(self): """Test for authorized users can access bucket list""" response = self.client.get(url_for('api.bucketlist_items', id=3), headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 200) def test_get_bucketlist_add_new_item_authorized(self): """Test for can add new item in the bucketlist """ new_item = {"item name": "New Item Bucketlist"} response = self.client.post(url_for('api.bucketlist_items', id=3), headers=self.get_api_headers(self.token), data=json.dumps(new_item)) self.assertEqual(response.status_code, 201) def test_get_bucketlist_no_bucket_list(self): """Test for bucketlist collection doesn't exist""" response = self.client.get(url_for('api.bucketlist_items', id=5), headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 404) def test_get_edit_bucketlist(self): """ Test for edit bucketlist collection""" edit_bucket_item = {"bucketlist_name": "Edited Bucketlist"} response = self.client.put(url_for('api.manage_bucketlist', id=3), headers=self.get_api_headers(self.token), data=json.dumps(edit_bucket_item)) response_data = json.loads(response.data) self.assertEqual(response.status_code, 201) def test_delete_bucketlist(self): """ Test for delete bucket list""" response = self.client.delete(url_for('api.manage_bucketlist', id=3), headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 204) def test_for_bucket_list_item_not_found(self): """ test for get bucketlist item route /api/v1/:id/items not found """ response = self.client.get(url_for('api.manage_bucketlist', id=5), headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 404) def test_for_url_not_found(self): """ test for none existing url within the api applicaito """ response = self.client.get(url_for('api.bucketlists') + '/custompage', headers=self.get_api_headers(self.token)) self.assertEqual(response.status_code, 404)