Best Python code snippet using tempest_python
test_models.py
Source:test_models.py
2from core.models import User, Notebook, Folder, NoteGroup, Member, Invite, Activity, Note, Rating, Comment3from django.db.utils import IntegrityError4from datetime import datetime5# Test utils.py6def create_test_user(7 name='João Cleber',8 mail='joao.cleber@celebridades.net',9 password='M0ld3d0r :3',10 bio='Apresentador João Cleber Fodão ð'11) -> User:12 """Create an user for testing"""13 return User.objects.create_user(name=name, email=mail, password=password, bio=bio)14def create_test_notebook(user: User) -> Notebook:15 """Create a notebook for testing"""16 return Notebook.objects.create(title="Test Notebook", owner=user)17def create_test_folder(notebook: Notebook, parent_folder: Folder = None) -> Folder:18 """Create a folder for testing"""19 return Folder.objects.create(title='Test Folder', notebook=notebook, parent_folder=parent_folder)20def create_test_member(user: User, notebook: Notebook) -> Member:21 """Create a member for testing"""22 return Member.objects.create(user=user, notebook=notebook)23def create_test_invite(member: Member, user: User) -> Invite:24 """Create an invite for testing"""25 return Invite.objects.create(member=member, user=user)26def create_test_activity(user: User, title: str, description: str) -> Activity:27 """Create an activity for testing"""28 return Activity.objects.create(user=user, title=title, description=description)29def create_test_note_group(parent_folder: Folder, title: str = 'Test NoteGroup') -> NoteGroup:30 return NoteGroup.objects.create(title=title, parent_folder=parent_folder)31def create_test_note(author: Member, note_group: NoteGroup, title: str = "Test Note") -> Note:32 """Create a note for testing"""33 return Note.objects.create(author=author, note_group=note_group, title=title)34class ModelTests(TestCase):35 """Test the models"""36 # User tests37 def test_user_creation_successful(self):38 """Test the creation of a user"""39 test_name = 'João Cleber'40 test_mail = 'joao.cleber@celebridades.net'41 test_password = 'M0ld3d0r :3'42 test_bio = 'Apresentador João Cleber Fodão ð'43 # Creating user "João Cleber"44 test_user = User.objects.create_user(name=test_name, email=test_mail, password=test_password, bio=test_bio)45 self.assertTrue(test_user.check_password(test_password), "Password check assertion")46 self.assertEqual(test_user.get_username(), test_user.email, "Check if the username field is the email")47 # Recovering user by email48 retrieved_user = User.objects.get(email=test_mail)49 self.assertEqual(retrieved_user, test_user, "Check user retrieval equality")50 self.assertTrue(retrieved_user.check_password(test_password), "Retrieved user password check assertion")51 def test_user_creation_email_normalizing(self):52 """Tests the domain normalization of the email"""53 in_email = 'joao.cleber@CElEbriDaDes.net'54 expected_email = 'joao.cleber@celebridades.net'55 user = User.objects.create_user(email=in_email, name="João Cleber", password="password")56 self.assertEqual(user.email, expected_email, "Assert the domain normalization of an email")57 def test_user_creation_invalid_fields(self):58 """Test the required user fields"""59 with self.assertRaises(ValueError, msg="Creating an user with invalid email"):60 User.objects.create_user(email=None, name="Zé Byke", password="password")61 with self.assertRaises(ValueError, msg="Creating an user with invalid name"):62 User.objects.create_user(email="zé@byke.net", name=None, password="password")63 with self.assertRaises(ValueError, msg="Creating an user with no password"):64 User.objects.create_user(email="cuca@beludo.net", name="Cuca Beludo", password=None)65 # Notebook Tests66 def test_notebook_creation(self):67 """Test the creation of a notebook"""68 test_user = create_test_user()69 test_title = 'Notebook 1'70 notebook = Notebook.objects.create(title=test_title, owner=test_user)71 self.assertEqual(notebook.creation_date.strftime("%D"), datetime.utcnow().strftime("%D"))72 notebook_saved = Notebook.objects.get(id=notebook.id)73 self.assertEqual(notebook_saved.title, test_title)74 self.assertEqual(notebook_saved.owner_id, test_user.id)75 self.assertEqual(str(notebook), test_title)76 def test_folder_creation(self):77 """Test the creation of a Folder"""78 test_user = create_test_user()79 test_notebook = create_test_notebook(test_user)80 root_folder_title = 'Anxiety'81 sub_folder_title = 'Peace'82 root_folder = Folder.objects.create(title=root_folder_title, notebook=test_notebook, parent_folder=None)83 self.assertEqual(root_folder.parent_folder, None)84 self.assertEqual(root_folder.notebook_id, test_notebook.id)85 self.assertEqual(root_folder.title, root_folder_title)86 sub_folder = Folder.objects.create(title=sub_folder_title, notebook=test_notebook, parent_folder=root_folder)87 self.assertEqual(sub_folder.parent_folder_id, root_folder.id)88 self.assertEqual(sub_folder.notebook_id, sub_folder.parent_folder.notebook_id)89 root_folder.refresh_from_db()90 sub_folders = root_folder.sub_folders.all()91 self.assertIn(sub_folder, sub_folders)92 def test_note_group_creation(self):93 """Test the creation of a NoteGroup"""94 test_user = create_test_user()95 test_notebook = create_test_notebook(test_user)96 test_folder = create_test_folder(test_notebook)97 test_title = 'Test Note Group'98 note_group = NoteGroup.objects.create(title=test_title, parent_folder=test_folder)99 self.assertEqual(note_group.title, test_title)100 self.assertEqual(note_group.parent_folder_id, test_folder.id)101 folders_groups = test_folder.note_groups.all()102 self.assertIn(note_group, folders_groups)103 # Member Tests104 def teste_member_creation(self):105 """Test the creation of a member"""106 test_user = create_test_user()107 test_owner = create_test_user(name='Ednaldo Pereira', mail='ednaldo@gmail.com', password='abuble', bio='brabo')108 test_notebook = create_test_notebook(test_owner)109 member = Member.objects.create(user=test_user, notebook=test_notebook)110 self.assertEqual(member.user, test_user)111 self.assertEqual(member.notebook, test_notebook)112 self.assertEqual(member.member_since.strftime("%D"), datetime.utcnow().strftime("%D"))113 # Invite Test114 def test_invite_creation(self):115 """Test the creation of an invite"""116 # Criação do dono do caderno e do caderno para criar um membro117 test_owner = create_test_user(name='Ednaldo', mail='ed@gmail.com', password='abuble', bio='gente boa')118 test_notebook = create_test_notebook(test_owner)119 # Criação do membro que irá enviar o convite120 test_member = create_test_member(test_owner, test_notebook)121 # Criação do usuário que irá receber o convite122 test_user = create_test_user()123 invite = Invite.objects.create(sender=test_member, receiver=test_user)124 self.assertEqual(invite.sender, test_member)125 self.assertEqual(invite.receiver, test_user)126 self.assertEqual(invite.invite_date.strftime("%D"), datetime.utcnow().strftime("%D"))127 # Activity Test128 def test_activity_creation(self):129 """Test the creation of an activity"""130 test_user = create_test_user()131 test_title = 'Atividade Teste'132 test_description = 'Essa atividade foi criada para fins de teste'133 activity = Activity.objects.create(user=test_user, title=test_title, description=test_description)134 self.assertEqual(activity.user, test_user)135 self.assertEqual(activity.description, test_description)136 self.assertEqual(activity.title, test_title)137 # Note Test138 def test_note_creation(self):139 """Test the creation of a note"""140 test_user = create_test_user()141 test_notebook = create_test_notebook(test_user)142 test_member = create_test_member(test_user, test_notebook)143 test_folder = create_test_folder(test_notebook)144 test_note_group = create_test_note_group(test_folder)145 test_title = "Some Note"146 test_note = Note.objects.create(author=test_member, note_group=test_note_group, title=test_title)147 self.assertEqual(test_note.author, test_member)148 self.assertEqual(test_note.creation_date.strftime("%D"), datetime.utcnow().strftime("%D"))149 self.assertEqual(test_note.title, test_title)150 self.assertEqual(test_note.content, "")151 self.assertIn(test_note, test_note_group.notes.all())152 self.assertIn(test_note, test_member.notes.all())153 self.assertIsNotNone(str(test_note))154 def test_rating_creation(self):155 """Test the creation of a rating"""156 test_user = create_test_user()157 test_notebook = create_test_notebook(test_user)158 test_member = create_test_member(test_user, test_notebook)159 test_folder = create_test_folder(test_notebook)160 test_note_group = create_test_note_group(test_folder)161 test_note = create_test_note(test_member, test_note_group)162 test_rating = Rating.objects.create(note=test_note, rating=8, rater=test_member)163 self.assertIsNotNone(str(test_rating))164 self.assertIn(test_rating, test_note.ratings.all())165 self.assertEqual(test_rating.rating, 8)166 self.assertIn(test_rating, test_member.rates.all())167 self.assertEqual(test_rating.rated_date.strftime("%D"), datetime.utcnow().strftime("%D"))168 with self.assertRaises(IntegrityError):169 Rating.objects.create(note=test_note, rating=8, rater=test_member)170 def test_comment_creation(self):171 """Test comment creation"""172 test_user = create_test_user()173 test_notebook = create_test_notebook(test_user)174 test_member = create_test_member(test_user, test_notebook)175 test_folder = create_test_folder(test_notebook)176 test_note_group = create_test_note_group(test_folder)177 test_note = create_test_note(test_member, test_note_group)178 test_comment = Comment.objects.create(note=test_note, commenter=test_member, message="Test comment")179 self.assertIsNotNone(str(test_comment))180 self.assertIn(test_comment, test_note.comments.all())181 self.assertIn(test_comment, test_member.comments.all())182 self.assertFalse(test_comment.solved)183 self.assertEqual(test_comment.creation_date.strftime("%D"), datetime.utcnow().strftime("%D"))184 def test_notebook_create_notebook(self):185 """Test the custom create_notebook method"""186 test_user = create_test_user()187 test_notebook: Notebook = Notebook.objects.create_notebook(title="Test title", owner=test_user)188 self.assertIsNotNone(test_notebook.id)189 Notebook.objects.get(id=test_notebook.id) # If not found, raises exception190 membership = Member.objects.get(notebook=test_notebook, user=test_user) # If not found, raises exception191 self.assertEqual(membership.role, Member.Roles.ADMIN) # Assert right role assignment...
test_logs.py
Source:test_logs.py
1from links.views import *2import pytest3from django.urls import reverse4from django.core.files.uploadedfile import SimpleUploadedFile5@pytest.mark.django_db6def test_login_success(client, create_test_user, caplog):7 test_user = create_test_user8 client.force_login(test_user)9 assert test_user.username + ' logged in via ip: ' in caplog.text10@pytest.mark.django_db11def test_login_fail(client, create_test_user_with_password, caplog):12 test_user = create_test_user_with_password13 username = test_user.username14 client.post('/accounts/login/', {'username': username, 'password': 'test1234'})15 assert 'login failed for: ' in caplog.text16 assert 'via ip: ' in caplog.text17@pytest.mark.django_db18def test_logout(client, create_test_user, caplog):19 test_user = create_test_user20 username = test_user.username21 client.force_login(test_user)22 client.logout()23 assert username + ' logged out via ip: ' in caplog.text24@pytest.mark.django_db25def test_home(client, create_test_user, caplog):26 test_user = create_test_user27 username = test_user.username28 client.force_login(test_user)29 client.get(reverse('home'))30 assert username + ' visited the home page' in caplog.text31@pytest.mark.django_db32def test_user_page_exist(client, create_test_user, caplog):33 test_user = create_test_user34 username = test_user.username35 client.force_login(test_user)36 client.get(reverse('userPage', kwargs={'username': username}))37 assert username + ' visited ' + username + '\'s page' in caplog.text38@pytest.mark.django_db39def test_user_page_not_exist(client, create_test_user, caplog):40 test_user = create_test_user41 username = test_user.username42 client.force_login(test_user)43 client.get(reverse('userPage', kwargs={'username': 'testing123'}))44 assert username + ' tried to visit a user\'s page that did not exist' in caplog.text45@pytest.mark.django_db46def test_collection_page_user_not_exist(client, create_test_user, caplog):47 test_user = create_test_user48 username = test_user.username49 client.force_login(test_user)50 client.get(reverse('collectionPage', kwargs={'username': 'test123', 'collection_name': 'Test collection1'}))51 assert username + ' tried to visit a user\'s collection page but the user did not exist' in caplog.text52@pytest.mark.django_db53def test_collection_page_collection_exist(client, create_test_collection, caplog):54 test_collection = create_test_collection55 test_user = test_collection.user56 username = test_user.username57 collection_name = test_collection.name58 client.force_login(test_user)59 client.get(reverse('collectionPage', kwargs={'username': 'test_user3', 'collection_name': 'Test collection1'}))60 assert username + ' visited ' + username + '\'s ' + collection_name + ' collection' in caplog.text61@pytest.mark.django_db62def test_collection_page_collection_not_exist(client, create_test_user, caplog):63 test_user = create_test_user64 username = test_user.username65 client.force_login(test_user)66 client.get(reverse('collectionPage', kwargs={'username': username, 'collection_name': 'Test collection1'}))67 assert username + ' tried to visit ' + username + '\'s collection that did not exist' in caplog.text68@pytest.mark.django_db69def test_link_create_form_valid(client, create_test_user, caplog):70 user = create_test_user71 username = user.username72 client.force_login(user)73 lcv = LinkCreateView()74 form = lcv.get_form_class()75 new_photo = SimpleUploadedFile(name='test_image.jpg',76 content=open('links/tests/test_data/background.jpg', 'rb').read(),77 content_type='image/jpeg')78 form = form(data={'hyperlink': 'https://twitter.com/',79 'website_name': 'Twitter',80 'image': new_photo})81 client.post(reverse('createLink'), data=form.data)82 assert username + ' created a link' in caplog.text83@pytest.mark.django_db84def test_link_delete_view(client, create_test_link, caplog):85 test_link = create_test_link86 test_user = test_link.user87 client.force_login(test_user)88 client.get(reverse('deleteLink', kwargs={'pk': test_link.id}))89 client.post(reverse('deleteLink', kwargs={'pk': test_link.id}))90 assert test_user.username + ' deleted a link' in caplog.text91@pytest.mark.django_db92def test_link_upload_view(client, create_test_link_with_image, caplog):93 test_link = create_test_link_with_image94 test_user = test_link.user95 client.force_login(test_user)96 new_photo = SimpleUploadedFile(name='test_image.jpg',97 content=open('links/tests/test_data/amazon.jpg', 'rb').read(),98 content_type='image/jpeg')99 client.post(reverse('uploadLink', kwargs={'pk': test_link.id}), data={'image': new_photo})100 assert test_user.username + ' updated a link\'s image' in caplog.text101@pytest.mark.django_db102def test_log_collection_create_view_with_multiple_links(client, create_test_links, caplog):103 links = create_test_links(3)104 test_user = links[0].user105 client.force_login(test_user)106 client.post(reverse('createCollection'), data={'name': 'abc',107 'user': test_user,108 'links': [link.id for link in links]})109 assert test_user.username + ' created a collection' in caplog.text110@pytest.mark.django_db111def test_log_collection_create_view_with_no_links(client, create_test_user, caplog):112 test_user = create_test_user113 client.force_login(test_user)114 client.post(reverse('createCollection'), data={'name': 'abc',115 'user': test_user})116 assert test_user.username + ' created a collection' in caplog.text117@pytest.mark.django_db118def test_log_collection_create_view_with_one_links(client, create_test_links, caplog):119 links = create_test_links(1)120 test_user = links[0].user121 client.force_login(test_user)122 client.post(reverse('createCollection'), data={'name': 'abc',123 'user': test_user,124 'links': [link.id for link in links]})125 assert test_user.username + ' created a collection' in caplog.text126@pytest.mark.django_db127def test_log_collection_detail_view(client, create_test_collection, caplog):128 test_collection = create_test_collection129 test_user = test_collection.user130 client.force_login(test_user)131 client.get(reverse('detailCollection', kwargs={'pk': test_collection.id}))132 assert test_user.username + ' looked at a collection' in caplog.text133@pytest.mark.django_db134def test_log_collection_delete_view_(client, create_test_collection, caplog):135 test_collection = create_test_collection136 test_user = test_collection.user137 client.force_login(test_user)138 client.post(reverse('deleteCollection', kwargs={'pk': test_collection.id}))139 assert test_user.username + ' deleted a collection' in caplog.text140@pytest.mark.django_db141def test_log_collection_update_view_remove_link(client, create_test_collection, caplog):142 test_collection = create_test_collection143 test_user = test_collection.user144 client.force_login(test_user)145 client.post(reverse('updateCollection', kwargs={'pk': test_collection.id}), data={})146 assert test_user.username + ' updated a collection' in caplog.text147@pytest.mark.django_db148def test_log_collection_link_delete_view(client, create_test_collection, caplog):149 test_collection = create_test_collection150 test_user = test_collection.user151 client.force_login(test_user)152 client.post(reverse('removeLink', kwargs={'pk': test_collection.id}),153 data={'link_id': test_collection.links.all()[:1].get().id})...
test_user.py
Source:test_user.py
...16 self.username = username17 self.email = email18 self.password = password19@pytest.fixture20def create_test_user():21 fake_profile = fake.simple_profile()22 image_id = f"https://storage.googleapis.com/{BUCKET_NAME}/No_image_available.svg.png"23 create_user(name=fake_profile['name'], username=fake_profile['username'], email=fake_profile['mail'],24 hashedpw=get_password_hash('test123'), image_id=image_id)25 user = get_user_by_email(email=fake_profile['mail'])26 return user27class TestUserClass:28 def test_create_user(self):29 """30 Tests the create_user function using Faker for fake profile info then, deletes the newly created user to save db31 space32 :return:33 """34 fake_profile = fake.simple_profile()...
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!!