0% found this document useful (0 votes)
17 views

Unit Testing

Uploaded by

sureshp3622
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit Testing

Uploaded by

sureshp3622
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Unit Testing

 Introduction

 Unit testing is a fundamental aspect of software testing where individual


components or functions of a software application are tested in isolation.
 By focusing on small, manageable parts of the application, unit testing helps
identify and fix bugs early in the development process, significantly improving
code quality and reliability.
 Unit tests are typically automated and written by developers using various
frameworks such as JUnit, NUnit, or pytest.

 Prerequisite of Unit Testing

 Understanding of the software development process.


 Knowledge of programming languages and development tools.
 Familiarity with the code base.
 Ability to write test cases and understand expected outcomes.
 Proficiency in using unit testing frameworks and tools.
 Awareness of best practices and guidelines for writing effective unit tests.
 Clear understanding of the purpose and goals of unit testing in the software
development lifecycle.

 What is a unit test?

Unit tests are automated and are run each time the code is changed to ensure that
new code does not break existing functionality. Unit tests are designed to validate
the smallest possible unit of code, such as a function or a method, and test it in
isolation from the rest of the system. This allows developers to quickly identify and
fix any issues early in the development process, improving the overall quality of the
software and reducing the time required for later testing.
 Objective of Unit Testing
 The objective of Unit Testing are follows
o To isolate a section of code.
o To verify the correctness of the code.
o To test every function and procedure.
o To fix bugs early in the development cycle and to save costs.
o To help the developers understand the code base and enable them to
make changes quickly.
o To help with code reuse.

 Types of Unit Testing

1. Manual Testing
2. Automation Testing
 To apply unit testing in your Django REST Framework (DRF) API,
you can follow these steps:

 Step 1: Set Up Your Testing Environment


o Create a Test Directory: Ensure you have a directory for tests in your
app. If you don’t have one, create a tests.py file or a tests/ directory
inside your app folder.
o Import Required Modules: In your test file, import the necessary
modules for testing. You’ll typically need TestCase from django.test
and some utilities from rest_framework.
 Step 2: Write Your Test Cases
o Extend TestCase: Create a class that extends django.test.TestCase. This class
will contain your test methods.
o Set Up Test Data: Use the setUp() method to create any test data you need
for your tests.
o Write Test Methods: Each test method should start with test_ and will
typically include:
o Making requests to your API (using self.client).
o Asserting the response status and data.

 Location of test File.


 Coding Sample of Unit Testing in Test file.

from django.test import TestCase


from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from barberAPI.models import BarberShopModel
from django.core.files.uploadedfile import SimpleUploadedFile
import uuid
import os

class BarberShopAPITest(TestCase):

def setUp(self):
self.client = APIClient()

def test_create_barbershop(self):
"""
Test for creating a barber shop via API
"""
url = reverse('barberRegisterPage') # Ensure this matches the URL
name in your urls.py
# Create a sample image file for logo upload
logo_path = 'E:\\Broader ai\\Carely-
backend\\servercarely\\media\\shopLogo\\2.jpg'
with open(logo_path, 'rb') as logo_file:
logo = SimpleUploadedFile(
name=os.path.basename(logo_path),
content=logo_file.read(),
content_type='image/jpeg'
)

random_uuid = uuid.uuid4()
data = {
"carely_barber_shop_id": random_uuid,
"carely_barber_shop_commercial_number": "34566",
"carely_barber_shop_name": "Vogue cut",
"carely_barber_shop_uploadLogo": logo,
"carely_barber_shop_type": "individual",
"carely_barber_shop_admin_email": "[email protected]",
"carely_barber_shop_admin_password": "John@1234"
}

response = self.client.post(url, data, format='multipart')


self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertIn("carely_barber_shop_id", response.data["data"])
def test_barbershop_name_required(self):
"""
Test for missing barber shop name
"""
url = reverse('barberRegisterPage')
random_uuid = uuid.uuid4()
data = {
"carely_barber_shop_id": random_uuid,
"carely_barber_shop_commercial_number": "34566",
"carely_barber_shop_name": "", # Missing shop name
"carely_barber_shop_type": "individual",
"carely_barber_shop_admin_email": "[email protected]",
"carely_barber_shop_admin_password": "John@1234"
}

response = self.client.post(url, data, format='json')


self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['message'], 'Barber shop name is
required')

def test_barbershop_email_validation(self):
"""
Test for invalid barber shop email
"""
url = reverse('barberRegisterPage')
random_uuid = uuid.uuid4()
data = {
"carely_barber_shop_id": random_uuid,
"carely_barber_shop_commercial_number": "34566",
"carely_barber_shop_name": "Vogue cut",
"carely_barber_shop_type": "individual",
"carely_barber_shop_admin_email": "invalid-email", # Invalid
email
"carely_barber_shop_admin_password": "John@1234"
}

response = self.client.post(url, data, format='json')


self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['message'], 'Invalid email address')

def test_duplicate_commercial_number(self):
"""
Test for duplicate barber shop commercial number
"""
# Create a barber shop first
random_uuid = uuid.uuid4()
BarberShopModel.objects.create(
carely_barber_shop_id = random_uuid,
carely_barber_shop_commercial_number="34566",
carely_barber_shop_name="Vogue cut",
carely_barber_shop_type="individual",
carely_barber_shop_admin_email="[email protected]",
carely_barber_shop_admin_password="hashed_password"
)

url = reverse('barberRegisterPage')

data = {
"carely_barber_shop_id": random_uuid,
"carely_barber_shop_commercial_number": "34566", # Duplicate
commercial number
"carely_barber_shop_name": "New Cut",
"carely_barber_shop_type": "individual",
"carely_barber_shop_admin_email": "[email protected]",
"carely_barber_shop_admin_password": "NewPass@123"
}

response = self.client.post(url, data, format='json')


self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response.data['message'], 'Barber shop commercial
number is already exits')

def test_invalid_password(self):
"""
Test for weak password
"""
url = reverse('barberRegisterPage')
random_uuid = uuid.uuid4()
data = {
"carely_barber_shop_id": random_uuid,
"carely_barber_shop_commercial_number": "34566",
"carely_barber_shop_name": "Vogue cut",
"carely_barber_shop_type": "individual",
"carely_barber_shop_admin_email": "[email protected]",
"carely_barber_shop_admin_password": "weakpass" # Weak password
}

response = self.client.post(url, data, format='json')


self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['message'], 'Password should contain
uppercase, lowercase, numbers and special characters')
Step 3: Run Your Tests
python manage.py test your_app_name

Step 4: Continuous Testing

1. Integration with CI/CD: Consider integrating your tests into a continuous


integration/continuous deployment (CI/CD) pipeline to automate testing
whenever you push changes.
2. Coverage Reports: Use tools like coverage.py to check test coverage and
ensure your tests adequately cover your codebase.

 Manually Approach in single file


import requests
import json

APIURL=" http://127.0.0.1:8000"
Reviewuserintoregister = f"{APIURL}/barberApis/BarberShopGet"

response = requests.post(Reviewuserintoregister)
print(response)

You might also like