
Module 5 Lesson 2: Integration Testing & Services
Do they play well together? Learn how to use GitLab 'Services' to spin up temporary databases and caches (like Redis or Postgres) during your integration tests.
Module 5 Lesson 2: Integration Testing & Services
Unit tests are local (they don't need a network). but Integration Tests need to talk to real databases and real services. GitLab uses the Services keyword to spin up these "Sidecar" containers.
1. What is a "Service"?
A service is a separate container that runs at the same time as your test job. They share a network, so your test can talk to the database using a simple hostname.
test-db:
stage: test
image: python:3.9
services:
- postgres:15-alpine # GitLab starts this automatically!
variables:
# Tell the postgres image how to setup
POSTGRES_DB: test_db
POSTGRES_USER: runner
POSTGRES_PASSWORD: password
script:
- pip install psycopg2-binary
# Your code connects to host "postgres"
- python run_integration_tests.py
2. Dynamic Aliases
If you want to use a specific name for your service:
services:
- name: redis:latest
alias: cache
Your app can now connect to http://cache:6379.
3. Why not use a "Mock"?
Mocks are fast, but they aren't Real.
- Integration tests catch things like: "Oh, Postgres 15 handles this date format differently than my mock did."
- They catch networking and permission bugs that unit tests miss.
4. The "Healthcheck" Pause
GitLab is smart. It won't start your script until the Service (e.g., Postgres) is "Ready." It waits for the port to open so your tests don't fail because the DB was still booting.
Exercise: The Sidecar Setup
- Create a job that uses the
redis:alpineservice. - In your script, try to
pingtheredishost. (You might need to installiputils-pingfirst). - Add a Postgres service. Pass a custom
POSTGRES_PASSWORDvariable. - Why is it a bad idea to use
servicesfor a "Long-running" server? (Hint: When do services stop?) - Research: How many
servicescan you have in a single job?
Summary
Integration testing with GitLab Services allows you to build a "Miniature World" for your tests. By spinning up real databases and caches for every commit, you ensure that your code doesn't just work on your machine, but effectively interacts with your entire infrastructure.
Next Lesson: Keeping it pretty: Code Linting and Style Checks.