Advertisement
fkudinov

Postman to Python - Api Testing

Dec 4th, 2024 (edited)
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.09 KB | Source Code | 0 0
  1. # ----------------   api_client.py ----------------
  2.  
  3. # pip install requests
  4. import time
  5. from requests import session
  6.  
  7.  
  8. class ApiClient:
  9.  
  10.     user_name = None
  11.     user_pass = None
  12.     user_id = None
  13.  
  14.     def __init__(self):
  15.         self.client = session()
  16.         self.host = "https://demoqa.com"
  17.  
  18.     def request(self, method, url, **kwargs) -> dict | None:
  19.         time.sleep(0.5)  # slow down not to ddos 3rd party server
  20.  
  21.         res = self.client.request(method, f"{self.host}/{url}", **kwargs)
  22.         res.raise_for_status()
  23.         if res.text:
  24.             return res.json()
  25.  
  26.     def get_books(self):
  27.         return self.request("GET", "BookStore/v1/Books")
  28.  
  29.     def create_user(self):
  30.         payload = {"userName": self.user_name,
  31.                    "password": self.user_pass}
  32.         return self.request("POST", "Account/v1/User", json=payload)
  33.  
  34.     def create_token(self):
  35.         payload = {"userName": self.user_name,
  36.                    "password": self.user_pass}
  37.         return self.request("POST", "Account/v1/GenerateToken", json=payload)
  38.  
  39.     def user_login(self):
  40.         payload = {"userName": self.user_name,
  41.                    "password": self.user_pass}
  42.         return self.request("POST", "Account/v1/Login", json=payload)
  43.  
  44.     def get_user(self):
  45.         return self.request("GET", f"Account/v1/User/{self.user_id}")
  46.  
  47.     def add_books(self, *isbns: str):
  48.         payload = {"userId": self.user_id,
  49.                    "collectionOfIsbns": [{"isbn": i} for i in isbns]}
  50.         return self.request("POST", "BookStore/v1/Books", json=payload)
  51.  
  52.     def delete_book(self, isbn):
  53.         payload = {"isbn": isbn,
  54.                    "userId": self.user_id}
  55.         return self.request("DELETE", "BookStore/v1/Book", json=payload)
  56.  
  57.     def swap_books(self, isbn1, isbn2):
  58.         payload = {"userId": self.user_id,
  59.                    "isbn": isbn2}
  60.         return self.request("PUT", f"BookStore/v1/Books/{isbn1}", json=payload)
  61.  
  62.     def delete_books(self):
  63.         params = {"UserId": self.user_id}
  64.         return self.request("DELETE", f"BookStore/v1/Books", params=params)
  65.  
  66.     def delete_user(self):
  67.         return self.request("DELETE", f"Account/v1/User/{self.user_id}")
  68.  
  69.     def setup(self, user_name, user_pass):
  70.         self.user_name = user_name
  71.         self.user_pass = user_pass
  72.         self.create_user()
  73.         self.create_token()
  74.  
  75.         res = self.user_login()
  76.         self.user_id = res["userId"]
  77.         self.client.headers["Authorization"] = f"Bearer {res['token']}"
  78.  
  79.  
  80.  
  81. # -------------  test_sample.py -----------------------
  82.  
  83.  
  84. import os
  85. import pytest
  86. from api_client import ApiClient
  87.  
  88. USER_NAME = os.environ.get("API_TEST_USER_NAME")
  89. PASSWORD = os.environ.get("API_TEST_USER_PASSWORD")
  90.  
  91.  
  92. @pytest.fixture
  93. def client():
  94.     client = ApiClient()
  95.     client.setup(USER_NAME, PASSWORD)
  96.     yield client
  97.     client.delete_user()
  98.  
  99.  
  100. @pytest.fixture(scope="session")
  101. def books():
  102.     return ApiClient().get_books()["books"]
  103.  
  104.  
  105. def test_full(client, books):
  106.     client.get_user()
  107.     client.add_books(books[0]["isbn"], books[1]["isbn"])
  108.     client.delete_book(books[0]["isbn"])
  109.     client.replace_book(books[1]["isbn"], books[2]["isbn"])
  110.     client.delete_books()
  111.  
  112.  
  113. def test_get_books():
  114.     res = ApiClient().get_books()
  115.     assert len(res["books"]) == 8
  116.  
  117.  
  118. def test_get_profile(client):
  119.     res = client.get_user()
  120.     assert res["userId"] == client.user_id
  121.     assert res["username"] == client.user_name
  122.     assert len(res["books"]) == 0
  123.  
  124.  
  125. def test_add_books(client, books):
  126.     isbn1 = books[0]["isbn"]
  127.     isbn2 = books[1]["isbn"]
  128.  
  129.     res = client.add_books(isbn1, isbn2)
  130.     assert res["books"] == [{'isbn': isbn1}, {'isbn': isbn2}]
  131.  
  132.     res = client.get_user()
  133.     assert len(res["books"]) == 2
  134.     assert res["books"][0]["isbn"] == isbn1
  135.     assert res["books"][1]["isbn"] == isbn2
  136.  
  137.  
  138. def test_delete_books(client, books):
  139.     isbn1 = books[0]["isbn"]
  140.     isbn2 = books[1]["isbn"]
  141.     client.add_books(isbn1, isbn2)
  142.  
  143.     client.delete_books()
  144.     res = client.get_user()
  145.     assert len(res["books"]) == 0
  146.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement