Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save freelancing-solutions/10edc55038ce2a48c485b16fdbdc69a3 to your computer and use it in GitHub Desktop.
Save freelancing-solutions/10edc55038ce2a48c485b16fdbdc69a3 to your computer and use it in GitHub Desktop.
Test Cases for FlaskAlchemy Models based on PyTest
# import unittest
import uuid, time
from .. import db, create_app
from flask import current_app
from ..library import config
def test_hireme_freelance_job_model():
from ..hireme.models import FreelanceJobModel
from ..users.models import UserModel
if not current_app:
app = create_app(config_class=config.TestingConfig)
app.app_context().push()
else:
app = current_app
app.testing = True
with app.app_context():
user_model_list = UserModel.query.limit(1).all()
if len(user_model_list) > 0:
user_instance = user_model_list[0]
uid = user_instance.uid
else:
uid = ""
assert False, "Could not retrieve user detail test failed"
project_name = "Website Development"
project_category = "Website"
description = "Develop my website/blog based on wordpress"
hours_to_complete = 24 * 7
currency = "R"
budget_allocated = 520
freelance_job_model = FreelanceJobModel(uid=uid,project_name=project_name,project_category=project_category,
description=description,est_hours_to_complete=hours_to_complete,currency=currency,budget_allocated=budget_allocated)
print("Testing hireme freelance jobs models")
assert isinstance(freelance_job_model,FreelanceJobModel), "Failed to created an instance of freelance model"
print("freelance job models are created correctly")
assert freelance_job_model.budget_allocated == budget_allocated , "Failed to set budget_allocated"
assert freelance_job_model.project_name == project_name , "Project Name set incorrectly"
assert freelance_job_model.description == description, "Failed to set description"
assert freelance_job_model.est_hours_to_complete == hours_to_complete, "Failed to set hours to complete"
assert freelance_job_model.currency == currency, "Failed to set currency"
assert freelance_job_model.budget_allocated == budget_allocated, "Failed to set budget allocated"
try:
db.session.add(freelance_job_model)
db.session.flush()
db.session.commit()
except Exception as error:
assert False, "Could not save freelance model to database"
freelance_job_mo = FreelanceJobModel.query.filter_by(uid=uid).first()
assert freelance_job_mo, "Cannot retrieve freelance job model from database"
assert freelance_job_mo == freelance_job_model, "Instance Values from database are not equal to created instances"
db.session.delete(freelance_job_model)
db.session.flush()
db.session.commit()
@freelancing-solutions
Copy link
Author

Why Test Python Programs

Creating a way to test your modules, units and programs is a very useful thing as it allows you to eliminate most bugs in your programs and can sometimes help you to avoid introducing bugs into your program later on.

using a testing framework in python such as PyTest or unittest involves writing test cases allowing you to test each aspect of your program with different input scenarios and edge cases in order to see or learn how your code can break, this also allows you to write defensive code, which means your overall code is more likely to have fewer bugs and also unlikely to fail in the future and also when more team members gets introduced into the project.

How to install PyTest and prepare your environment for testing

**install PyTest into your environment**
  • pip install pytest

    Create a module named tests

  •     **Create a folder named tests**
    
  •     **Create a file inside the folder and name it` __init__.py` in order to turn the folder into a module**
    

    Create PyTest Test Cases

  •     **Inside the tests module create test cases**
    
  •     **Test cases are created inside python files with names starting with `test_[test-case-name].py`**
    
  •     **replace [test-case-name] with the name of the test case example `test_users_model.py`**
    

    How to run tests

  •     **Inside the folder/module for tests execute the following command `py.test`**
    
  •     **All your tests will run**
    

@freelancing-solutions
Copy link
Author

freelancing-solutions commented Mar 9, 2021

Coding your Python Flask App to enable Testing

Your app needs to be configured into modules in order to allow testing,
Modules are easier to import into test cases or test files inside your tests module.
They also allow for you to create different instances of your app in order to test your app with different configurations

You will need to configure your app to use
Blueprints routes
current_app and create_app (this allows you to run your app in different contexts, or from any other module)

Your Flask Entry Point file should look more or less like this one

import os
from main import create_app, db
from main.library.config import Config

app = create_app()
app.app_context().push()

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))

**This allows most of the configuration code to reside on a separate module, and launched through create_app function
thereby giving you the ability to import this function at any point in any python program and create another app instance**

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment