Best Python code snippet using localstack_python
test_forms.py
Source:test_forms.py
1# -*- coding: utf8 -*-2# This file is part of PyBossa.3#4# Copyright (C) 2014 SF Isle of Man Limited5#6# PyBossa is free software: you can redistribute it and/or modify7# it under the terms of the GNU Affero General Public License as published by8# the Free Software Foundation, either version 3 of the License, or9# (at your option) any later version.10#11# PyBossa is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU Affero General Public License for more details.15#16# You should have received a copy of the GNU Affero General Public License17# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.18from wtforms import ValidationError19from nose.tools import raises20from flask import current_app21from default import Test, db, with_context22from pybossa.forms.forms import (RegisterForm, LoginForm, EMAIL_MAX_LENGTH,23 USER_NAME_MAX_LENGTH, USER_FULLNAME_MAX_LENGTH)24from pybossa.forms import validator25from pybossa.repositories import UserRepository26from factories import UserFactory27user_repo = UserRepository(db)28class TestValidator(Test):29 def setUp(self):30 super(TestValidator, self).setUp()31 with self.flask_app.app_context():32 self.create()33 @raises(ValidationError)34 def test_unique(self):35 """Test VALIDATOR Unique works."""36 with self.flask_app.test_request_context('/'):37 f = LoginForm()38 f.email.data = self.email_addr39 u = validator.Unique(user_repo.get_by, 'email_addr')40 u.__call__(f, f.email)41 @raises(ValidationError)42 def test_not_allowed_chars(self):43 """Test VALIDATOR NotAllowedChars works."""44 with self.flask_app.test_request_context('/'):45 f = LoginForm()46 f.email.data = self.email_addr + "$"47 u = validator.NotAllowedChars()48 u.__call__(f, f.email)49 @raises(ValidationError)50 def test_comma_separated_integers(self):51 """Test VALIDATOR CommaSeparatedIntegers works."""52 with self.flask_app.test_request_context('/'):53 f = LoginForm()54 f.email.data = '1 2 3'55 u = validator.CommaSeparatedIntegers()56 u.__call__(f, f.email)57 @with_context58 @raises(ValidationError)59 def test_reserved_names_account_signin(self):60 """Test VALIDATOR ReservedName for account URLs"""61 form = RegisterForm()62 form.name.data = 'signin'63 val = validator.ReservedName('account', current_app)64 val(form, form.name)65 @with_context66 @raises(ValidationError)67 def test_reserved_names_project_published(self):68 """Test VALIDATOR ReservedName for project URLs"""69 form = RegisterForm()70 form.name.data = 'category'71 val = validator.ReservedName('project', current_app)72 val(form, form.name)73class TestRegisterForm(Test):74 def setUp(self):75 super(TestRegisterForm, self).setUp()76 self.fill_in_data = {'fullname': 'Tyrion Lannister', 'name': 'mylion',77 'email_addr': 'tyrion@casterly.rock',78 'password':'secret', 'confirm':'secret'}79 fields = ['fullname', 'name', 'email_addr', 'password', 'confirm']80 @with_context81 def test_register_form_contains_fields(self):82 form = RegisterForm()83 for field in self.fields:84 assert form.__contains__(field), 'Field %s is not in form' %field85 @with_context86 def test_register_form_validates_with_valid_fields(self):87 form = RegisterForm(**self.fill_in_data)88 assert form.validate()89 @with_context90 def test_register_form_unique_name(self):91 form = RegisterForm(**self.fill_in_data)92 user = UserFactory.create(name='mylion')93 assert not form.validate()94 assert "The user name is already taken" in form.errors['name'], form.errors95 @with_context96 def test_register_name_length(self):97 self.fill_in_data['name'] = 'a'98 form = RegisterForm(**self.fill_in_data)99 error_message = "User name must be between 3 and %s characters long" % USER_NAME_MAX_LENGTH100 assert not form.validate()101 assert error_message in form.errors['name'], form.errors102 @with_context103 def test_register_name_allowed_chars(self):104 self.fill_in_data['name'] = '$#&\/|'105 form = RegisterForm(**self.fill_in_data)106 assert not form.validate()107 assert "$#&\\/| and space symbols are forbidden" in form.errors['name'], form.errors108 @with_context109 def test_register_name_reserved_name(self):110 self.fill_in_data['name'] = 'signin'111 form = RegisterForm(**self.fill_in_data)112 assert not form.validate()113 assert u'This name is used by the system.' in form.errors['name'], form.errors114 @with_context115 def test_register_form_unique_email(self):116 form = RegisterForm(**self.fill_in_data)117 user = UserFactory.create(email_addr='tyrion@casterly.rock')118 assert not form.validate()119 assert "Email is already taken" in form.errors['email_addr'], form.errors120 @with_context121 def test_register_email_length(self):122 self.fill_in_data['email_addr'] = ''123 form = RegisterForm(**self.fill_in_data)124 error_message = "Email must be between 3 and %s characters long" % EMAIL_MAX_LENGTH125 assert not form.validate()126 assert error_message in form.errors['email_addr'], form.errors127 @with_context128 def test_register_email_valid_format(self):129 self.fill_in_data['email_addr'] = 'notanemail'130 form = RegisterForm(**self.fill_in_data)131 assert not form.validate()132 assert "Invalid email address." in form.errors['email_addr'], form.errors133 @with_context134 def test_register_fullname_length(self):135 self.fill_in_data['fullname'] = 'a'136 form = RegisterForm(**self.fill_in_data)137 error_message = "Full name must be between 3 and %s characters long" % USER_FULLNAME_MAX_LENGTH138 assert not form.validate()139 assert error_message in form.errors['fullname'], form.errors140 @with_context141 def test_register_password_required(self):142 self.fill_in_data['password'] = ''143 form = RegisterForm(**self.fill_in_data)144 assert not form.validate()145 assert "Password cannot be empty" in form.errors['password'], form.errors146 @with_context147 def test_register_password_missmatch(self):148 self.fill_in_data['confirm'] = 'badpasswd'149 form = RegisterForm(**self.fill_in_data)150 assert not form.validate()...
test_dashboard_task_task_run.py
Source:test_dashboard_task_task_run.py
1# -*- coding: utf8 -*-2# This file is part of PyBossa.3#4# Copyright (C) 2015 SF Isle of Man Limited5#6# PyBossa is free software: you can redistribute it and/or modify7# it under the terms of the GNU Affero General Public License as published by8# the Free Software Foundation, either version 3 of the License, or9# (at your option) any later version.10#11# PyBossa is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU Affero General Public License for more details.15#16# You should have received a copy of the GNU Affero General Public License17# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.18from pybossa.dashboard.jobs import new_tasks_week, new_task_runs_week19from pybossa.dashboard.data import format_new_task_runs, format_new_tasks20from pybossa.core import db21from datetime import datetime, timedelta22from factories.taskrun_factory import TaskRunFactory, AnonymousTaskRunFactory23from factories.task_factory import TaskFactory24from default import Test, with_context25from mock import patch, MagicMock26class TestDashBoardNewTask(Test):27 @with_context28 @patch('pybossa.dashboard.jobs.db')29 def test_materialized_view_refreshed(self, db_mock):30 """Test JOB dashboard materialized view is refreshed."""31 result = MagicMock()32 result.exists = True33 results = [result]34 db_mock.slave_session.execute.return_value = results35 res = new_tasks_week()36 assert db_mock.session.execute.called37 assert res == 'Materialized view refreshed'38 @with_context39 @patch('pybossa.dashboard.jobs.db')40 def test_materialized_view_created(self, db_mock):41 """Test JOB dashboard materialized view is created."""42 result = MagicMock()43 result.exists = False44 results = [result]45 db_mock.slave_session.execute.return_value = results46 res = new_tasks_week()47 assert db_mock.session.commit.called48 assert res == 'Materialized view created'49 @with_context50 def test_new_tasks(self):51 """Test JOB dashboard returns new task."""52 TaskFactory.create()53 new_tasks_week()54 sql = "select * from dashboard_week_new_task;"55 results = db.session.execute(sql)56 for row in results:57 assert row.day_tasks == 1, row.day_tasks58 @with_context59 @patch('pybossa.dashboard.data.db')60 def test_format_new_tasks_emtpy(self, db_mock):61 """Test format new tasks empty works."""62 db_mock.slave_session.execute.return_value = []63 new_tasks_week()64 res = format_new_tasks()65 assert len(res['labels']) == 166 day = datetime.utcnow().strftime('%Y-%m-%d')67 assert res['labels'][0] == day68 assert len(res['series']) == 169 assert res['series'][0][0] == 0, res['series'][0][0]70 @with_context71 def test_format_new_tasks(self):72 """Test format new tasks works."""73 TaskFactory.create()74 new_tasks_week()75 res = format_new_tasks()76 assert len(res['labels']) == 177 day = datetime.utcnow().strftime('%Y-%m-%d')78 assert res['labels'][0] == day79 assert len(res['series']) == 180 assert res['series'][0][0] == 1, res['series'][0][0]81class TestDashBoardNewTaskRuns(Test):82 @with_context83 @patch('pybossa.dashboard.jobs.db')84 def test_materialized_view_refreshed(self, db_mock):85 """Test JOB dashboard materialized view is refreshed."""86 result = MagicMock()87 result.exists = True88 results = [result]89 db_mock.slave_session.execute.return_value = results90 res = new_task_runs_week()91 assert db_mock.session.execute.called92 assert res == 'Materialized view refreshed'93 @with_context94 @patch('pybossa.dashboard.jobs.db')95 def test_materialized_view_created(self, db_mock):96 """Test JOB dashboard materialized view is created."""97 result = MagicMock()98 result.exists = False99 results = [result]100 db_mock.slave_session.execute.return_value = results101 res = new_task_runs_week()102 assert db_mock.session.commit.called103 assert res == 'Materialized view created'104 @with_context105 def test_new_task_runs(self):106 """Test JOB dashboard returns new task runs."""107 day = datetime.utcnow() - timedelta(days=2)108 TaskRunFactory.create(finish_time=day.isoformat())109 day = datetime.utcnow() - timedelta(days=1)110 TaskRunFactory.create(finish_time=day.isoformat())111 new_task_runs_week()112 sql = "select * from dashboard_week_new_task_run;"113 results = db.session.execute(sql)114 for row in results:115 assert row.day_task_runs == 1, row.day_task_runs116 @with_context117 @patch('pybossa.dashboard.data.db')118 def test_format_new_task_runs_emtpy(self, db_mock):119 """Test format new task_runs empty works."""120 db_mock.slave_session.execute.return_value = []121 new_task_runs_week()122 res = format_new_task_runs()123 assert len(res['labels']) == 1124 day = datetime.utcnow().strftime('%Y-%m-%d')125 assert res['labels'][0] == day, res126 assert len(res['series']) == 1127 assert res['series'][0][0] == 0, res['series'][0][0]128 @with_context129 def test_format_new_task_runs(self):130 """Test format new task_runs works."""131 TaskRunFactory.create()132 AnonymousTaskRunFactory.create()133 new_task_runs_week()134 res = format_new_task_runs()135 assert len(res['labels']) == 1136 day = datetime.utcnow().strftime('%Y-%m-%d')137 assert res['labels'][0] == day, res138 assert len(res['series']) == 1...
test_pricelist.py
Source:test_pricelist.py
...32 # applying the computation manually33 context = {}34 public_context = dict(context, pricelist=self.public_pricelist.id)35 pricelist_context = dict(context, pricelist=self.sale_pricelist_id.id)36 usb_adapter_without_pricelist = self.usb_adapter.with_context(public_context)37 usb_adapter_with_pricelist = self.usb_adapter.with_context(pricelist_context)38 self.assertEqual(usb_adapter_with_pricelist.price, usb_adapter_without_pricelist.price*0.9)39 datacard_without_pricelist = self.datacard.with_context(public_context)40 datacard_with_pricelist = self.datacard.with_context(pricelist_context)41 self.assertEqual(datacard_with_pricelist.price, datacard_without_pricelist.price-0.5)42 # Make sure that changing the unit of measure does not break the unit43 # price (after converting)44 unit_context = dict(context, pricelist=self.sale_pricelist_id.id, uom=self.uom_unit_id)45 dozen_context = dict(context, pricelist=self.sale_pricelist_id.id, uom=self.uom_dozen_id)46 usb_adapter_unit = self.usb_adapter.with_context(unit_context)47 usb_adapter_dozen = self.usb_adapter.with_context(dozen_context)48 self.assertAlmostEqual(usb_adapter_unit.price*12, usb_adapter_dozen.price)49 datacard_unit = self.datacard.with_context(unit_context)50 datacard_dozen = self.datacard.with_context(dozen_context)51 # price_surcharge applies to product default UoM, here "Units", so surcharge will be multiplied52 self.assertAlmostEqual(datacard_unit.price*12, datacard_dozen.price)53 def test_20_pricelist_uom(self):54 # Verify that the pricelist rules are correctly using the product's default UoM55 # as reference, and return a result according to the target UoM (as specific in the context)56 kg, tonne = self.uom_kgm_id, self.uom_ton.id57 tonne_price = 10058 # make sure 'tonne' resolves down to 1 'kg'.59 self.uom_ton.write({'rounding': 0.001})60 # setup product stored in 'tonnes', with a discounted pricelist for qty > 3 tonnes61 spam_id = self.usb_adapter.copy({62 'name': '1 tonne of spam',63 'uom_id': self.uom_ton.id,64 'uom_po_id': self.uom_ton.id,65 'list_price': tonne_price,66 'type': 'consu'67 })68 self.env['product.pricelist.item'].create({69 'pricelist_id': self.public_pricelist.id,70 'applied_on': '0_product_variant',71 'compute_price': 'formula',72 'base': 'list_price', # based on public price73 'min_quantity': 3, # min = 3 tonnes74 'price_surcharge': -10, # -10 EUR / tonne75 'product_id': spam_id.id76 })77 pricelist = self.public_pricelist78 def test_unit_price(qty, uom, expected_unit_price):79 spam = spam_id.with_context({'uom': uom})80 unit_price = pricelist.with_context({'uom': uom}).get_product_price(spam, qty, False)81 self.assertAlmostEqual(unit_price, expected_unit_price, msg='Computed unit price is wrong')82 # Test prices - they are *per unit*, the quantity is only here to match the pricelist rules!83 test_unit_price(2, kg, tonne_price / 1000.0)84 test_unit_price(2000, kg, tonne_price / 1000.0)85 test_unit_price(3500, kg, (tonne_price - 10) / 1000.0)86 test_unit_price(2, tonne, tonne_price)...
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!!