1+ import time
12import pytest
2- from src .api_client import APIClient
3- from src .database import DatabaseConnection
4-
5- @pytest .fixture (scope = "module" )
6- def api_client ():
7- client = APIClient (base_url = "https://fakerestapi.azurewebsites.net/" )
8- yield client
3+ import requests
4+ from requests .adapters import HTTPAdapter
5+ from urllib3 .util .retry import Retry
6+ from config import settings
97
8+ class HttpClient :
9+ """Cliente HTTP focado em testes: timeout, retry e rate-limit simples."""
10+ def __init__ (self , base_url : str , connect_timeout : float , read_timeout : float , retry_total : int , rate_sleep : float ):
11+ self .base_url = base_url .rstrip ("/" )
12+ self .session = requests .Session ()
13+ retry = Retry (
14+ total = retry_total ,
15+ backoff_factor = 0.5 ,
16+ status_forcelist = [429 , 500 , 502 , 503 , 504 ],
17+ allowed_methods = ["GET" ],
18+ respect_retry_after_header = True ,
19+ )
20+ adapter = HTTPAdapter (max_retries = retry , pool_connections = 10 , pool_maxsize = 10 )
21+ self .session .mount ("https://" , adapter )
22+ self .session .mount ("http://" , adapter )
23+ self .session .headers .update ({"Accept" : "application/json" })
24+ self .timeout = (connect_timeout , read_timeout )
25+ self .rate_sleep = rate_sleep
1026
11- @pytest .fixture (scope = "module" )
12- def db_connection ():
13- """
14- Fixture to create a conection with PostreSQL DB.
15-
16- Set up the env variables or parameters as needed:
17- - DB_HOST: localhost
18- - DB_DATABASE: seu_banco
19- - DB_USER: seu_usuario
20- - DB_PASSWORD: sua_senha
21- - DB_PORT: 5432
22- """
23- db = DatabaseConnection (
24- host = "localhost" ,
25- database = "testdb" ,
26- user = "user" ,
27- password = "1234" ,
28- port = 5432
29- )
30- yield db
31- db .close ()
27+ def get (self , path_or_url : str , ** kwargs ) -> requests .Response :
28+ """GET com base_url opcional e respeito a rate-limit."""
29+ if path_or_url .startswith ("http://" ) or path_or_url .startswith ("https://" ):
30+ url = path_or_url
31+ else :
32+ url = f"{ self .base_url } /{ path_or_url .lstrip ('/' )} "
33+ time .sleep (self .rate_sleep ) # rate-limit simples
34+ return self .session .get (url , timeout = self .timeout , ** kwargs )
35+
36+ @pytest .fixture (scope = "session" )
37+ def base_url () -> str :
38+ return settings .BASE_URL
39+
40+ @pytest .fixture (scope = "session" )
41+ def http () -> HttpClient :
42+ return HttpClient (
43+ base_url = settings .BASE_URL ,
44+ connect_timeout = settings .CONNECT_TIMEOUT ,
45+ read_timeout = settings .READ_TIMEOUT ,
46+ retry_total = settings .RETRY_TOTAL ,
47+ rate_sleep = settings .RATE_LIMIT_SLEEP ,
48+ )
0 commit comments