Best Python code snippet using localstack_python
test_main.py
Source:test_main.py
1import json2from unittest import mock3from api.app import app4def test_get(snapshot):5 response = app.test_client().get("/")6 snapshot.assert_match(response.status_code)7 snapshot.assert_match(response.data)8def test_health(snapshot):9 response = app.test_client().get("/health")10 snapshot.assert_match(response.status_code)11 snapshot.assert_match(response.data)12def test_loan_no_api_key_provided(snapshot):13 response = app.test_client().post("/loan", data={"name": "Everton Tomalok"})14 data_resp = response.data.decode("utf-8")15 status_code = response.status_code16 snapshot.assert_match(status_code)17 snapshot.assert_match(data_resp)18@mock.patch("api.app.is_api_key_valid")19def test_loan_error_first_check(is_api_key_valid, snapshot):20 is_api_key_valid.return_value = True21 response = app.test_client().post(22 "/loan",23 data={"name": "Everton Tomalok"},24 headers={"api-key": "its a valid key"},25 )26 data_resp = json.loads(response.data.decode("utf-8"))27 snapshot.assert_match(response.status_code)28 snapshot.assert_match(data_resp)29@mock.patch("api.app.is_api_key_valid")30def test_loan_saving(is_api_key_valid, snapshot):31 is_api_key_valid.return_value = True32 json_obj = {33 "name": "Everton Tomalok",34 "cpf": "123.456.789-00",35 "birthdate": "15/08/1992",36 "amount": "1000.50",37 "terms": "6",38 "income": "12000.00",39 }40 response = app.test_client().post(41 "/loan?testingCase=true", data=json_obj, headers={"api-key": "its a valid key"}42 )43 data_resp = json.loads(response.data.decode("utf-8"))44 snapshot.assert_match(response.status_code)45 snapshot.assert_match("id" in data_resp.keys())46@mock.patch("api.app.is_api_key_valid")47def test_loan_saving_error_model(is_api_key_valid, snapshot):48 is_api_key_valid.return_value = True49 json_obj = {50 "name": "Everton Tomalok",51 "cpf": "123.456.789-00",52 "birthdate": "15/08/1992",53 "amount": "1000.50",54 "terms": "7",55 "income": "12000.00",56 }57 response = app.test_client().post(58 "/loan?testingCase=true", data=json_obj, headers={"api-key": "its a valid key"}59 )60 data_resp = json.loads(response.data.decode("utf-8"))61 snapshot.assert_match(response.status_code)62 snapshot.assert_match(data_resp)63@mock.patch("api.model.database.Database.find_loan")64def test_loan_status(find_loan):65 loan_status_value = {66 "_id": "c5b91560-1c63-43c4-91ec-925ba8a3fb87",67 "name": "Everton Tomalok",68 "cpf": "12345678900",69 "birthdate": "1992-08-15",70 "amount": "4000",71 "terms": 6,72 "income": "10000",73 }74 find_loan.return_value = loan_status_value75 response = app.test_client().get(76 "/loan/c5b91560-1c63-43c4-91ec-925ba8a3fb87?testingCase=true"77 )78 data_resp = json.loads(response.data.decode("utf-8"))...
app.py
Source:app.py
1from flask import Flask, jsonify, request2from flask_cors import CORS, cross_origin3from database.db_model import Database4from os import path5app = Flask(__name__)6cors = CORS(app)7app.config['CORS_HEADERS'] = 'Content-Type'8db = Database()9def read_api_key_from_file():10 basepath = path.dirname(__file__)11 api_key_filepath = path.abspath(path.join(basepath, "..", "api_key.txt"))12 api_key_file = open(api_key_filepath, "r")13 for line in api_key_file:14 FILE_API_KEY = line.replace("\n", "").split(" ")[1]15 api_key_file.close()16 return FILE_API_KEY17API_KEY = read_api_key_from_file()18def validate_api_key(req):19 if req.headers.get('API_KEY') == API_KEY:20 return True21 return False22@app.route('/reserveFrog', methods=['POST'])23def reserveFrog():24 is_api_key_valid = validate_api_key(request)25 if is_api_key_valid:26 frog_data = request.json27 frog_reservation = db.reserve_frog(frog_data)28 if frog_reservation:29 return {'msg': f'Frog {frog_data["frog_id"]} reserved'}30 return {'msg': 'Frog NOT reserved'}31 return {32 'msg': 'Invalid api key'33 }34@app.route('/getFreeFrog')35def getFreeFrog():36 is_api_key_valid = validate_api_key(request)37 if is_api_key_valid:38 free_frog_data = db.get_free_frog()39 if free_frog_data:40 return {41 'amount': free_frog_data['amount'],42 'frog_id': free_frog_data['frog_id']43 }44 is_any_frog_reserved = db.check_if_any_frog_is_reserved()45 if is_any_frog_reserved:46 return {47 'msg': 'All frogs reserved'48 }49 return {50 'msg': 'All frogs sold out'51 }52 return {53 'msg': 'Invalid api key'54 }55if __name__ == '__main__':...
Predict.py
Source:Predict.py
...7from flask_restful import Resource8from flask import request, current_app9from resources.TrainModel import TrainModelResource10class Predict(Resource):11 def is_api_key_valid(self, key):12 train_model = TrainModelResource.get_by_id(key)13 if 'Fmdev-Api-Key' not in request.headers:14 return False15 if request.headers['Fmdev-Api-Key'] == train_model.api_key:16 return True17 return False18 def load_model(self, filename):19 path = f"{current_app.config.get('TRAIN_MODELS')}/{filename}.sav"20 loaded_model = joblib.load(open(path, 'rb'))21 return loaded_model22 def post(self, key):23 try:24 is_api_key_valid = self.is_api_key_valid(key)25 if is_api_key_valid == False:26 return {'msg': 'Fmdev-Api-Key is not valid'}, 40127 payload = request.get_json()28 x_test = pd.DataFrame(payload['data']) 29 model = self.load_model(filename=key)30 predict = model.predict(x_test)31 data_predicted = predict.tolist()32 TrainModelResource.update_predict(key)33 return { 'data': data_predicted }34 except:35 traceback.print_exc()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!