MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Testing Flask with Pytest, Gunicorn & Docker Deployment0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
10.1Testing Flask with Pytest, Gunicorn & Docker Deployment
HomeTutorialsFlaskTesting Flask with Pytest, Gunicorn & Docker Deployment

Testing Flask with Pytest, Gunicorn & Docker Deployment

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Building an enterprise Flask application is only half the battle; ensuring code reliability through automated testing and packaging it for production deployment completes the engineering lifecycle.

In this lesson, we explore automated unit testing with Pytest, WSGI production serving with Gunicorn, and containerization with Docker.


1. Automated Testing with Pytest & Flask Test Client

Flask provides a built-in test client that simulates HTTP requests against your application without starting a live web server socket.

1pip install pytest pytest-flask

Pytest Fixtures (tests/conftest.py):

1import pytest
2from app import create_app
3from app.extensions import db
4from models import User
5 
6@pytest.fixture
7def app():
8 # Instantiate app with TestingConfig (in-memory SQLite)
9 test_app = create_app("testing")
10
11 with test_app.app_context():
12 db.create_all()
13 # Seed test user
14 user = User(username="testuser", email="test@example.com")
15 user.password = "ValidPassword123"
16 db.session.add(user)
17 db.session.commit()
18
19 yield test_app
20
21 db.session.remove()
22 db.drop_all()
23 
24@pytest.fixture
25def client(app):
26 # Returns simulated HTTP client
27 return app.test_client()

Writing Unit & Integration Tests (tests/test_auth.py):

1def test_home_page_returns_200(client):
2 response = client.get("/")
3 assert response.status_code == 200
4 assert b"MSK Institute" in response.data
5 
6def test_user_login_success(client):
7 response = client.post("/auth/login", data={
8 "username": "testuser",
9 "password": "ValidPassword123"
10 }, follow_redirects=True)
11 assert response.status_code == 200
12 assert b"Welcome back!" in response.data
13 
14def test_protected_route_requires_login(client):
15 response = client.get("/dashboard")
16 # Redirects to login page with 302
17 assert response.status_code == 302
18 assert "/auth/login" in response.headers["Location"]

Run tests in your terminal:

1pytest -v

2. Production WSGI Server: Gunicorn

In production, never use flask run or python app.py. Deploy using Gunicorn (Green Unicorn), a production-grade pre-fork worker WSGI server:

1pip install gunicorn

Run Gunicorn pointing to your WSGI callable:

1gunicorn --workers 4 --bind 0.0.0.0:8000 "wsgi:app"

Worker Sizing Formula:

Recommended Gunicorn workers formula: (2 x CPU_Cores) + 1. For a 2-core server: (2 x 2) + 1 = 5 workers.


3. Containerizing Flask with Docker

A Docker container bundles the application, Python runtime, system libraries, and dependencies into an immutable image.

Production Dockerfile:

1# Multi-stage production build
2FROM python:3.12-slim AS base
3 
4ENV PYTHONUNBUFFERED=1 \
5 PYTHONDONTWRITEBYTECODE=1 \
6 PIP_NO_CACHE_DIR=1
7 
8WORKDIR /app
9 
10# Install system dependencies
11RUN apt-get update && apt-get install -y --no-install-recommends \
12 gcc libpq-dev && \
13 rm -rf /var/lib/apt/lists/*
14 
15# Install Python requirements
16COPY requirements.txt .
17RUN pip install --upgrade pip && pip install -r requirements.txt
18 
19# Copy application source code
20COPY . .
21 
22# Create non-root user for security
23RUN useradd -m appuser && chown -R appuser:appuser /app
24USER appuser
25 
26EXPOSE 8000
27 
28# Start Gunicorn server
29CMD ["gunicorn", "--workers", "4", "--bind", "0.0.0.0:8000", "wsgi:app"]

4. Multi-Container Orchestration with docker-compose.yml

Connect Flask, PostgreSQL, and Redis:

1version: '3.8'
2 
3services:
4 web:
5 build: .
6 ports:
7 - "8000:8000"
8 environment:
9 - FLASK_ENV=production
10 - SECRET_KEY=super-secure-production-secret-key
11 - DATABASE_URL=postgresql://msk_user:msk_pass@db:5432/msk_prod
12 - CELERY_BROKER_URL=redis://redis:6379/0
13 depends_on:
14 - db
15 - redis
16 
17 db:
18 image: postgres:16-alpine
19 environment:
20 POSTGRES_USER: msk_user
21 POSTGRES_PASSWORD: msk_pass
22 POSTGRES_DB: msk_prod
23 volumes:
24 - postgres_data:/var/lib/postgresql/data
25 
26 redis:
27 image: redis:alpine
28 ports:
29 - "6379:6379"
30 
31volumes:
32 postgres_data:

Start the entire production stack:

1docker compose up -d --build

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does Flask's app.test_client() provide for automated testing?
Question 2
What does passing follow_redirects=True to client.post() accomplish?
Question 3
What is the recommended formula for calculating Gunicorn worker counts on a server?
Question 4
Why should a Dockerfile create and switch to a non-root user (USER appuser)?
Question 5
What command launches a multi-container stack defined in docker-compose.yml in detached background mode?

Related Lessons

Previous LessonNext Lesson
Performance Caching with Flask-CachingNone

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
Previous
PreviousPrevNext