TTime/testing.py
2024-03-17 03:46:16 +01:00

75 lines
2 KiB
Python

import requests
import string
import random
def randomString(len=10):
"""Generate a random string of fixed length"""
letters = string.ascii_lowercase
return "".join(random.choice(letters) for i in range(len))
# Defined once per test run
username = randomString()
token = None
# The base URL of the API
base_url = "http://localhost:8080"
# Endpoint to test
registerPath = base_url + "/api/register"
loginPath = base_url + "/api/login"
addProjectPath = base_url + "/api/project"
# Posts the username and password to the register endpoint
def register(username: string, password: string):
print("Registering with username: ", username, " and password: ", password)
response = requests.post(
registerPath, json={"username": username, "password": password}
)
print(response.text)
return response
# Posts the username and password to the login endpoint
def login(username: string, password: string):
print("Logging in with username: ", username, " and password: ", password)
response = requests.post(
loginPath, json={"username": username, "password": password}
)
print(response.text)
return response
def test_login():
response = login(username, "always_same")
assert response.status_code == 200, "Login failed"
print("Login successful")
return response.json()["token"]
def test_create_user():
response = register(username, "always_same")
assert response.status_code == 200, "Registration failed"
print("Registration successful")
def test_add_project():
loginResponse = login(username, "always_same")
token = loginResponse.json()["token"]
projectName = randomString()
response = requests.post(
addProjectPath,
json={"name": projectName, "description": "This is a project"},
headers={"Authorization": "Bearer " + token},
)
print(response.text)
assert response.status_code == 200, "Add project failed"
print("Add project successful")
if __name__ == "__main__":
test_create_user()
test_login()
test_add_project()