def register_user(email, name, password, password2): """ Register the user to the database :param email: the email of the user :param name: the name of the user :param password: the password of user :param password2: another password input to make sure the input is correct :return: an error message if there is any, or None if register succeeds """ user = User.query.filter_by(email=email).first() if user: return "User existed" if password != password2: return "The passwords do not match" if len(email) < 1: return "Email format error" if len(password) < 1: return "Password not strong enough" hashed_pw = generate_password_hash(password, method='sha256') # store the encrypted password rather than the plain password new_user = User(email=email, name=name, password=hashed_pw) db.session.add(new_user) db.session.commit() return None
def test_sell_ticket_duplicate_name(self): """ Duplicate name | user=<user in DB> name="Not Unique" quantity=1 price=10.00 expiryDate=date(2030, 1, 1) | Error: "A ticket with that name already exists." """ # The most straightforward way to have a ticket with a duplicate name # is to just insert the same ticket into the DB twice. # Prepare DB new_user = User() new_user.name = TEST_USER.name new_user.email = TEST_USER.email new_user.password = TEST_USER.password new_user.balance = TEST_USER.balance db.session.add(new_user) db.session.commit() # Set up parameters user = new_user name = "Not Unique" quantity = 1 price = 10.00 expiryDate = date(2030, 1, 1) # Call function ret_value = sell_ticket(user, name, quantity, price, expiryDate) # Check return value assert ret_value == False # Call function ret_value = sell_ticket(user, name, quantity, price, expiryDate) # Check return value assert ret_value == "A ticket with that name already exists."
def register_user(email, name, password, password2): """ Register the user to the database :param email: the email of the user :param name: the name of the user :param password: the password of user :param password2: another password input to make sure the input is correct :return: an error message if there is any, or None if register succeeds """ hashed_pw = generate_password_hash(password, method='sha256') # store the encrypted password rather than the plain password new_user = User(email=email, name=name, password=hashed_pw, balance=5000) db.session.add(new_user) db.session.commit() return None
def test_get_user_valid_email(self): """ Input Partion: valid email """ # Test is started with clean table. No need to remove data #Add test user to database hashed_pw = generate_password_hash('q1w2e3Q!W@E#', method='sha256') test_user = User(email='*****@*****.**', name='Test Email Input', password=hashed_pw, balance=5000) db.session.add(test_user) #Get user by email and assert equal to the test user user = get_user("*****@*****.**") self.assert_equal(user, test_user) #Clean up by deleting test user db.session.delete(test_user)
def setup(self): db.drop_all() db.create_all() # Create the state of the application to make it able to buy a ticket for a new user. # This allows the test to be independent from the ability to sell a ticket. # Remember this test is to test the full ability to create a user and buy a ticket not to sell one. owner = User(name="test", email="*****@*****.**", balance=5000, password=generate_password_hash('Test1234!', method='sha256')) ticket = Ticket(name="Test", quantity=2, price=20, email="*****@*****.**") db.session.add(ticket) db.session.add(owner) db.session.commit()
def register_user(email: str, name: str, password: str, password2: str): """ Register the user to the database :param email: the email of the user :param name: the name of the user :param password: the password of user :param password2: another password input to make sure the input is correct :return: an error message if there is any, or None if register succeeds """ email = email.strip() name = name.strip().lower() password = password.strip() password2 = password2.strip() user = User.query.filter_by(email=email).first() if user: return "This email is already in use." name_validation_error = validate_name(name) if not name_validation_error == None: return name_validation_error password_validation_error = validate_password(password) if not password_validation_error['state']: return password_validation_error['msg'] if password != password2: return "The passwords do not match." if not validate_email(email): return 'Invalid Email.' hashed_pw = generate_password_hash(password, method='sha256') # store the encrypted password rather than the plain password new_user = User(email=email, name=name, password=hashed_pw, balance=5000) db.session.add(new_user) db.session.commit() return None
def register_user(email, name, password, password2): """ Register the user to the database :param email: the email of the user :param name: the name of the user :param password: the password of user :param password2: another password input to make sure the input is correct :return: True if registration succeeds, otherwise False """ hashed_pw = generate_password_hash(password, method='sha256') # store the encrypted password rather than the plain password new_user = User(email=email, name=name, password=hashed_pw, balance=5000) db.session.add(new_user) try: db.session.commit() return True except Exception as e: db.session.rollback() # Rollback the current transaction in progress db.session.flush() # Reset non-commited .add() return False
def register_user(email, name, password, password2): """ Register the user to the database :param email: the email of the user :param name: the name of the user :param password: the password of user :param password2: another password input to make sure the input is correct :return: an error message if there is any, or None if register succeeds """ errors = [] # checks if email is valid format if not validate_email(email): errors.append("email format is incorrect") # checks if password is valid format if not validate_password(password): errors.append("password format is incorrect") # checks if passwords match if password != password2: errors.append("passwords do not match") # chechs if username has valid formats if not validate_username(name): errors.append("username format is incorrect") # check if email has been used before user = get_user(email) if user: errors.append("this email has been ALREADY used") # generate password hash hashed_pw = generate_password_hash(password, method='sha256') # do not create user if there are any errorsx if len(errors) > 0: return errors # store the encrypted password rather than the plain password new_user = User(email=email, name=name, password=hashed_pw, balance=5000.0) db.session.add(new_user) db.session.commit() return [] # no errors
def test_validate_ticket_inputs(self): assert validate_ticket_inputs("Test Ticket", 11, "20990101", 50, User(balance=5000)) == None assert validate_ticket_inputs( "TestTicket!", 11, "20990101", 50, User(balance=5000)) == "Name must be alphanumeric" assert validate_ticket_inputs( "Test", 11, "20990101", 50, User(balance=5000) ) == "Name length must be between 6 and 60 characters" assert validate_ticket_inputs( "Test this really super long ticket name that violates rule 1 woohoo", 11, "20990101", 50, User(balance=5000) ) == "Name length must be between 6 and 60 characters" assert validate_ticket_inputs( "Test Ticket", 11, "19990101", 50, User(balance=5000)) == "This ticket has expired" assert validate_ticket_inputs( "Test Ticket", 11, "20990101", 0, User(balance=5000)) == "Please select 1 to 100 tickets" assert validate_ticket_inputs( "Test Ticket", 11, "20990101", 255, User(balance=5000)) == "Please select 1 to 100 tickets"
def test_sell_ticket_user_not_in_db(self): """ User object that doesn't exist in database | user=<user not in DB> name="Unique" quantity=1 price=10.00 expiryDate=date(2030, 1, 1) | Internal Error: user does not exist in database """ # Prepare DB new_user = User() new_user.name = TEST_USER.name new_user.email = TEST_USER.email new_user.password = TEST_USER.password new_user.balance = TEST_USER.balance # Skip adding new_user to DB # Set up parameters user = new_user name = "Unique" quantity = 1 price = 10.00 expiryDate = date(2030, 1, 1) # Call function ret_value = sell_ticket(user, name, quantity, price, expiryDate) # Check return value assert ret_value == "Internal Error: user does not exist in database"
def test_sell_ticket_expiryDate_bad_type(self): """ Non-date type expiryDate parameter | user=<user in DB> name="Unique" quantity=1 price=10.00 expiryDate=None | Internal Error: 'expiryDate' must be of type 'date' """ # Prepare DB new_user = User() new_user.name = TEST_USER.name new_user.email = TEST_USER.email new_user.password = TEST_USER.password new_user.balance = TEST_USER.balance db.session.add(new_user) db.session.commit() # Set up parameters user = new_user name = "Unique" quantity = 1 price = 10.00 expiryDate = None # Call function ret_value = sell_ticket(user, name, quantity, price, expiryDate) # Check return value assert ret_value == "Internal Error: 'expiryDate' must be of type 'date'"
def test_sell_ticket_valid_with_fraction(self): """ All inputs valid, price with fractional part | user=<user in DB> name="Unique" quantity=1 price=12.34 expiryDate=date(2030, 1, 1) | No error """ # Prepare DB new_user = User() new_user.name = TEST_USER.name new_user.email = TEST_USER.email new_user.password = TEST_USER.password new_user.balance = TEST_USER.balance db.session.add(new_user) db.session.commit() # Set up parameters user = new_user name = "Unique" quantity = 1 price = 12.34 expiryDate = date(2030, 1, 1) # Call function ret_value = sell_ticket(user, name, quantity, price, expiryDate) # Check return value assert ret_value == False
def test_sell_ticket_user_bad_type(self): """ Non-User type user parameter | user=None name="Unique" quantity=1 price=10.00 expiryDate=date(2030, 1, 1) | Internal Error: 'user' must be of type 'User' """ # Prepare DB new_user = User() new_user.name = TEST_USER.name new_user.email = TEST_USER.email new_user.password = TEST_USER.password new_user.balance = TEST_USER.balance db.session.add(new_user) db.session.commit() # Set up parameters user = None name = "Unique" quantity = 1 price = 10.00 expiryDate = date(2030, 1, 1) # Call function ret_value = sell_ticket(user, name, quantity, price, expiryDate) # Check return value assert ret_value == "Internal Error: 'user' must be of type 'User'"
from unittest.mock import patch from qa327.models import db, User from qa327.backend import login_user """ This white-box test uses condition coverage. With login_user there is one if statement to watch out for, and two conditions. (not user): true or false (not check_password_hash(user.password, password)): true or false Both cannot be true at the same time, so this test will cover (true, false), (false, true), (false, false) """ test_user = User(email='*****@*****.**', name='Tester Zero', password='******', balance=5000) @patch('qa327.backend.get_user', return_value=None) def test_login_user_exist_false(self): """ In this case, the first condition will be true, meaning the or statement is true """ return login_user(test_user.email, test_user.password) == None @patch('qa327.backend.get_user', return_value=test_user) def test_login_password_match_false(self): """ In this case, the second condition will be true, meaning the or statement is true
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User, Tickets from werkzeug.security import generate_password_hash, check_password_hash valid_test_user_email = "*****@*****.**" valid_test_user_password = "******" # Mock a sample user test_user = User(id=1, email=valid_test_user_email, name='test_frontend', password=generate_password_hash(valid_test_user_password), balance=5000) # Mock some sample tickets test_tickets = [ Tickets(email='*****@*****.**', name="t1", date='24/12/2020', quantity='1', price='100') ] @patch('qa327.backend.get_user', return_value=test_user) @patch('qa327.backend.get_all_tickets', return_value=test_tickets) class test_R5(BaseCase):
The tests will only test the frontend portion of the program, by patching the backend to return specific values. For example: @patch('qa327.backend.get_user', return_value=test_user) Will patch the backend get_user function (within the scope of the current test case) so that it return 'test_user' instance below rather than reading the user from the database. Annotate @patch before unit tests can mock backend methods (for that testing function) """ # Moch a sample user test_user = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('AdnanJivanji11$')) # Moch some sample tickets test_tickets = [{'name': 't1', 'price': '100'}] class SellFormTest(BaseCase): #This function checks whether index page shows message when ticket name is not alphanumeric @patch('qa327.backend.get_user', return_value=test_user) def test_ticket_alphanumeric(self, *_): self.open(base_url + '/logout') #open login page self.open(base_url + '/login') #fill email and password
The tests will only test the frontend portion of the program, by patching the backend to return specfic values. For example: @patch('qa327.backend.get_user', return_value=test_user) Will patch the backend get_user function (within the scope of the current test case) so that it return 'test_user' instance below rather than reading the user from the database. Annotate @patch before unit tests can mock backend methods (for that testing function) """ # Moch a sample user test_user = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('Test_frontend', method='sha256')) # Moch some sample tickets test_tickets = [{'name': 't1', 'price': '100'}] class FrontEndHomePageTest(BaseCase): @patch('qa327.backend.get_user', return_value=test_user) @patch('qa327.backend.get_all_tickets', return_value=test_tickets) def test_login_success(self, *_): """ This is a sample front end unit test to login to home page and verify if the tickets are correctly listed. """ # open login page
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User, Ticket from werkzeug.security import generate_password_hash, check_password_hash # Moch a sample user test_user = User(email='*****@*****.**', name='test_user', password=generate_password_hash('Test!!'), balance=5000) # Moch some sample tickets test_tickets = Ticket(title='TestTest', quantity=50, price=50, expDate=20201212) class R3Test(BaseCase): # R3.1 If the user is not logged in, redirect to login page def test_R3_1(self, *_): self.open(base_url + '/logout') self.open(base_url + '/login') self.assert_element("#login-header") self.assert_text("Log In", "#login-header") # R3.2 This page shows a header 'Hi {}'.format(user.name)
import pytest from seleniumbase import BaseCase import qa327.backend as bn from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User from werkzeug.security import generate_password_hash, check_password_hash # integration testing: the test case interacts with the # browser, and test the whole system (frontend+backend). # Moch a sample user test_user = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('KingstonOntario2$'), balance=5000) @pytest.mark.usefixtures('server') class Registered(BaseCase): def register(self): """register new user""" self.open(base_url + '/register') self.type("#email", "*****@*****.**") self.type("#name", "Lia Mason") self.type("#password", "KingstonOntario2$") self.type("#password2", "KingstonOntario2$") self.click('input[type="submit"]') def login(self): """ Login to Swag Labs and verify that login was successful. """
from qa327.models import db, User, Form, Ticket from werkzeug.security import generate_password_hash, check_password_hash import requests """ This file defines all buy function unit tests for the frontend homepage. The tests will only test the frontend portion of the program, by patching the backend to return specfic values. For example: @patch('qa327.backend.get_user', return_value=test_user) Will patch the backend get_user function (within the scope of the current test case) so that it return 'test_user' instance below rather than reading the user from the database. Annotate @patch before unit tests can mock backend methods (for that testing function) """ # Mock a sample user test_user = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('Test_frontend@'), balance=500) # Mock a user that will not have enough money to buy a ticket test_poor_user = User(email='*****@*****.**', name='namepoor', password=generate_password_hash('Name_register@1'), balance=10) # Mock some sample tickets test_ticket = Ticket(name='t1', price=100, quantity=2, email='*****@*****.**', date='20200223') test_tickets = [ Ticket(name='t1',
from unittest.mock import patch from qa327.models import db, User, Ticket from werkzeug.security import generate_password_hash, check_password_hash dateTime = date.today() dateTime = dateTime + timedelta(days=10) future_date = dateTime.strftime("%Y\t%m%d") format_date = dateTime.strftime("%Y-%m-%d") # Moch a sample user fake = Faker() email = fake.email() name = fake.name() # Mock a sample user test_user = User(email="*****@*****.**", name='test_sellerpage', password=generate_password_hash('test_Frontend!2'), balance=5000) test_tickets = [{ 'ticket_name': 'testTicket', 'ticket_price': '15', 'num_tickets': '15', 'ticket_date': format_date, 'ticket_owner': '*****@*****.**' }, { 'ticket_name': 'ticket_info_correct', 'ticket_price': '35', 'num_tickets': '80', 'ticket_date': format_date, 'ticket_owner': '*****@*****.**' }]
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User, Ticket from werkzeug.security import generate_password_hash, check_password_hash test_user = User(email='*****@*****.**', name='validuser', password=generate_password_hash('123ABCxyz*')) wrong_email = '*****@*****.**' wrong_password = '******' valid_email = '*****@*****.**' valid_password = '******' invalid_emails = [ 'has [email protected]', '*****@*****.**', '*****@*****.**', 'has\\[email protected]', 'has"double"*****@*****.**', 'wacky)([email protected]', '*****@*****.**', '@test.com', 'nodomain.com', ' ', '*****@*****.**', 'local@$special#chars!%^&*.com', 'local@_unscoredomain_.com', '*****@*****.**', 'local@' ] invalid_passwords = [
from seleniumbase import BaseCase from werkzeug.security import generate_password_hash from qa327_test.conftest import base_url from qa327.models import User, Ticket # Mock a sample user TEST_USER = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('test_frontend'), balance=500) TEST_USER_SELLER = User(email='*****@*****.**', name='test_seller', password=generate_password_hash('Password99!'), balance=500) # Mock a sample ticket TEST_TICKET = Ticket(name='helloworld', seller=TEST_USER_SELLER, price=20, quantity=20, expires="20220101") class GeekBaseCase(BaseCase): ''' Selenium base case with some GeekSeek utilities ''' def assert_flash(self, text): '''asserts that message exists in flashes'''
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User from werkzeug.security import generate_password_hash, check_password_hash """ This file defines all unit tests for logging out. """ # Mock a sample user test_user = User(email='*****@*****.**', name='test_logout', password=generate_password_hash('TeStL0g0uT!')) # Mock some sample tickets test_tickets = [{ 'name': 't1', 'quantity': 1, 'contact': '*****@*****.**', 'price': 100 }, { 'name': 't2', 'quantity': 100, 'contact': '*****@*****.**', 'price': 10 }] class FrontEndHomePageTest(BaseCase):
from qa327.models import db, User, TicketInfo from werkzeug.security import generate_password_hash, check_password_hash """ This file defines unit tests for the frontend homepage. The tests will only test the frontend portion of the program, by patching the backend to return specfic values. For example: @patch('qa327.backend.get_user', return_value=test_user) Will patch the backend get_user function (within the scope of the current test case) so that it return 'test_user' instance below rather than reading the user from the database. Annotate @patch before unit tests can mock backend methods (for that testing function) """ # Mock a smple user (login) test_user_login = User(email='*****@*****.**', name='LetsTestL', password=generate_password_hash('Tester327!'), balance=10000) # Moch some sample tickets test_tickets = TicketInfo(email='*****@*****.**', name='t1', quantity=1, price=100, date='20210408') class TestR4(BaseCase): # Test Case R4.0.1 @pytest.mark.timeout(60) @patch('qa327.backend.get_user', return_value=test_user_login)
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from unittest.mock import patch from qa327.models import db, User, Ticket from werkzeug.security import generate_password_hash, check_password_hash """ This file defines all unit tests for buying tickets. """ test_user = User(email='*****@*****.**', name='testfrontend', password=generate_password_hash('123ABCxyz*'), balance=200) test_ticket = Ticket(name='t2', email='*****@*****.**', quantity=5, price=50, expiration_date=20221231) valid_names = ['ticket', 't3', 't3 Name'] invalid_names = [' t3', 't3:', 't3 '] lengthy = 'veryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryveryverylongname' non_lengthy = 'notverylongname' valid_quantity = [1, 50, 100]
The tests will only test the frontend portion of the program, by patching the backend to return specfic values. For example: @patch('qa327.backend.get_user', return_value=test_user) Will patch the backend get_user function (within the scope of the current test case) so that it return 'test_user' instance below rather than reading the user from the database. Annotate @patch before unit tests can mock backend methods (for that testing function) """ # Mock a sample user test_user = User(email='*****@*****.**', name='test_frontend', password=generate_password_hash('Testfrontend123!'), balance=5000) # Mock some sample tickets test_tickets = [{ 'name': 't1', 'price': '100', 'email': '*****@*****.**', 'date': '20200901' }] class FrontEndHomePageTest(BaseCase): # Test Case R2.1 - If the user has logged in, redirect back to the user profile page @patch('qa327.backend.get_user', return_value=test_user)
import pytest from seleniumbase import BaseCase from qa327_test.conftest import base_url from qa327.models import db, User, Ticket import qa327.backend as bn # integration testing: the test case interacts with the # browser, and test the whole system (frontend+backend). test_user = User(email='*****@*****.**', name='test frontend', password='******', balance=5000) test_ticket = Ticket(owner='*****@*****.**', name='test ticket', quantity="1", price="20", date="20210901") @pytest.mark.usefixtures('server') class Integration(BaseCase): def register(self): """register new user""" self.open(base_url + '/register') self.type("#email", test_user.email) self.type("#name", test_user.name) self.type("#password", test_user.password) self.type("#password2", test_user.password) self.click('input[type="submit"]')
import pytest from seleniumbase import BaseCase from qa327.models import db, User, Ticket from qa327_test.conftest import base_url from unittest.mock import patch from werkzeug.security import generate_password_hash, check_password_hash test_user = User(email='*****@*****.**', name='test_user', password=generate_password_hash('test_frontendA1$'), balance=100) test_user2 = User(email='*****@*****.**', name='test_user', password=generate_password_hash('test_frontendA1$'), balance=5000) test_ticket = Ticket(name='test ticket', owner=1, qty=100, price=1, exp='20201119') test_ticket2 = Ticket(name='test ticket', owner=1, qty=10, price=15, exp='20201119') test_ticket3 = Ticket(name='test ticket 3', owner=1,
import pytest from seleniumbase import BaseCase from qa327.models import db, User, Ticket from qa327_test.conftest import base_url from unittest.mock import patch from werkzeug.security import generate_password_hash, check_password_hash test_user = User(email='*****@*****.**', name='test_user', password=generate_password_hash('test_frontendA1$')) test_ticket = Ticket(name='test ticket', owner=1, qty=10, price=15, exp='20201119') class R4Test1(BaseCase): @patch('qa327.backend.get_user', return_value=test_user) def test_r4_5_2_1(self, *_): #logout if logged in self.open(base_url + '/logout') #login self.open(base_url + '/login') #enter user credentials self.type("#email", "*****@*****.**") self.type("#password", "test_frontendA1$") self.click("input[type='submit']") self.open(base_url) #make ticket