Merge pull request #16 from ThomasRubini/tests

This commit is contained in:
Thomas Rubini 2023-01-05 15:46:16 +01:00 committed by GitHub
commit 5dd60303cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 98 additions and 60 deletions

View File

@ -4,6 +4,15 @@ from truthseeker import app
test_app = app.test_client() test_app = app.test_client()
class TestException(Exception):
__test__ = False
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
############################################################################### ###############################################################################
# # # #
# # # #
@ -21,15 +30,12 @@ def createGame(user:User):
data = {"username":user.username} data = {"username":user.username}
responseObject = test_app.post("/api/v1/createGame",data=data) responseObject = test_app.post("/api/v1/createGame",data=data)
if responseObject.status_code != 200: if responseObject.status_code != 200:
print("status code is not 200") raise TestException("status code is not 200")
raise Exception("status code is not 200")
content = responseObject.json content = responseObject.json
if content is None: if content is None:
print("content is none") raise TestException("Response is null")
raise Exception("Response is null") if content["error"] != 0:
if content["status"] != "ok": raise TestException("backend returned an error: "+content["msg"])
print(content["status"])
raise Exception("Status is not ok")
user.isAdmin = True user.isAdmin = True
return content["game_id"] return content["game_id"]
@ -38,27 +44,23 @@ def joinGame(user:User,game_id:str):
data = {"username":user.username,"game_id":game_id} data = {"username":user.username,"game_id":game_id}
responseObject = test_app.post("/api/v1/joinGame",data=data) responseObject = test_app.post("/api/v1/joinGame",data=data)
if responseObject.status_code != 200: if responseObject.status_code != 200:
print("status code is not 200") raise TestException("status code is not 200")
raise Exception("status code is not 200")
content = responseObject.json content = responseObject.json
if content is None: if content is None:
raise Exception("Response is null") raise TestException("Response is null")
if content["status"] != "ok": if content["error"] != 0:
print(content["status"]) raise TestException("backend returned an error: "+content["msg"])
raise Exception("Status is not ok")
return True return True
def startGame(user:User): def startGame(user:User):
responseObject = test_app.post("/api/v1/startGame") responseObject = test_app.post("/api/v1/startGame")
if responseObject.status_code != 200: if responseObject.status_code != 200:
print("status code is not 200") raise TestException("status code is not 200")
raise Exception("status code is not 200")
content = responseObject.json content = responseObject.json
if content is None: if content is None:
raise Exception("Response is null") raise TestException("Response is null")
if content["status"] != "ok": if content["error"] != 0:
print(content["status"]) raise TestException("backend returned an error: "+content["msg"])
raise Exception("Status is not ok")
return True return True
@ -96,23 +98,23 @@ def test_that_two_person_having_the_same_pseudo_creating_two_games_results_in_tw
def test_that_not_sending_a_username_results_in_an_error(): def test_that_not_sending_a_username_results_in_an_error():
responseObject = test_app.post("/api/v1/createGame") responseObject = test_app.post("/api/v1/createGame")
assert responseObject.status_code == 200 assert responseObject.status_code == 200
assert responseObject.json["status"] != "ok" assert responseObject.json["error"] != 0
def test_that_sending_a_empty_username_results_in_an_error(): def test_that_sending_a_empty_username_results_in_an_error():
user = User("") user = User("")
with pytest.raises(Exception) as e: with pytest.raises(TestException) as e:
createGame(user) createGame(user)
assert "Status is not ok" in str(e.value)
def test_that_a_too_long_username_results_in_an_error(): def test_that_a_too_long_username_results_in_an_error():
user = User("Le test unitaire est un moyen de vérifier quun extrait de code fonctionne correctement. Cest lune des procédures mises en oeuvre dans le cadre dune méthodologie de travail agile. ") user = User("Le test unitaire est un moyen de vérifier quun extrait de code fonctionne correctement. Cest lune des procédures mises en oeuvre dans le cadre dune méthodologie de travail agile. ")
assert createGame(user) == None with pytest.raises(TestException) as e:
createGame(user)
def test_that_username_that_contains_non_alphanumerics_results_in_an_error(): def test_that_username_that_contains_non_alphanumerics_results_in_an_error():
user = User("я русский пират") user = User("я русский пират")
assert createGame(user) == None with pytest.raises(TestException) as e:
createGame(user)
############################################################################### ###############################################################################
# # # #
@ -138,41 +140,48 @@ def test_that_two_person_can_join_a_game():
def test_that_people_cant_join_if_the_username_is_already_used(): def test_that_people_cant_join_if_the_username_is_already_used():
game_id = createGame(User("neoreille")) game_id = createGame(User("neoreille"))
joinGame(User("neosomse"),game_id) joinGame(User("neosomse"),game_id)
assert joinGame(User("neosomse"),game_id) == False with pytest.raises(TestException) as e:
joinGame(User("neosomse"),game_id)
def test_that_people_joining_without_sending_any_data_results_in_an_error(): def test_that_people_joining_without_sending_any_data_results_in_an_error():
game_id = createGame(User("neoxyde")) game_id = createGame(User("neoxyde"))
responseObject = test_app.post("/api/v1/joinGame") responseObject = test_app.post("/api/v1/joinGame")
assert responseObject.status_code == 200 assert responseObject.status_code == 200
assert responseObject.json["status"] != "ok" assert responseObject.json["error"] != 0
def test_that_people_joining_without_sending_a_game_id_results_in_an_error(): def test_that_people_joining_without_sending_a_game_id_results_in_an_error():
data={"username":"neomblic"} data={"username":"neomblic"}
responseObject = test_app.post("/api/v1/joinGame",data=data) responseObject = test_app.post("/api/v1/joinGame",data=data)
assert responseObject.status_code == 200 assert responseObject.status_code == 200
assert responseObject.json["status"] != "ok" assert responseObject.json["error"] != 0
def test_that_people_joining_without_sending_an_username_still_results_in_an_error(): def test_that_people_joining_without_sending_an_username_still_results_in_an_error():
game_id = createGame(User("neonyx")) game_id = createGame(User("neonyx"))
data={"game_id":game_id} data={"game_id":game_id}
responseObject = test_app.post("/api/v1/joinGame",data=data) responseObject = test_app.post("/api/v1/joinGame",data=data)
assert responseObject.status_code == 200 assert responseObject.status_code == 200
assert responseObject.json["status"] != "ok" assert responseObject.json["error"] != 0
def test_that_people_joining_with_an_empty_username_still_results_in_an_error(): def test_that_people_joining_with_an_empty_username_still_results_in_an_error():
game_id = createGame(User("neodeur")) game_id = createGame(User("neodeur"))
user = User("") user = User("")
assert joinGame(user,game_id) == False
with pytest.raises(TestException) as e:
joinGame(user,game_id)
def test_that_people_joining_aving_an_username_that_contains_non_alphanumerics_still_results_in_an_error(): def test_that_people_joining_aving_an_username_that_contains_non_alphanumerics_still_results_in_an_error():
game_id = createGame(User("neobservateur")) game_id = createGame(User("neobservateur"))
user = User("Я брат русского пирата") user = User("Я брат русского пирата")
assert joinGame(user,game_id) == False
with pytest.raises(TestException) as e:
joinGame(user,game_id)
def test_that_people_joining_aving_a_too_long_username_still_results_in_an_error(): def test_that_people_joining_aving_a_too_long_username_still_results_in_an_error():
game_id = createGame(User("neordre")) game_id = createGame(User("neordre"))
user = User("Les tests unitaires sont généralement effectués pendant la phase de développement des applications mobiles ou logicielles. Ces tests sont normalement effectués par les développeurs, bien quà toutes fins pratiques, ils puissent également être effectués par les responsables en assurance QA.") user = User("Les tests unitaires sont généralement effectués pendant la phase de développement des applications mobiles ou logicielles. Ces tests sont normalement effectués par les développeurs, bien quà toutes fins pratiques, ils puissent également être effectués par les responsables en assurance QA.")
assert joinGame(user,game_id) == False
with pytest.raises(TestException) as e:
joinGame(user,game_id)
############################################################################### ###############################################################################
@ -191,21 +200,19 @@ def test_that_people_joining_aving_a_too_long_username_still_results_in_an_error
def test_that_people_can_start_a_game(): def test_that_people_can_start_a_game():
owner = User("neAUBERGINE") owner = User("neAUBERGINE")
game_id = createGame(owner) game_id = createGame(owner)
assert startGame(owner) == True startGame(owner)
def test_that_a_started_game_cannot_be_started_again(): def test_that_a_started_game_cannot_be_started_again():
with pytest.raises(Exception) as e: owner = User("neosteopathie")
owner = User("neosteopathie") game_id = createGame(owner)
game_id = createGame(owner) startGame(owner)
with pytest.raises(TestException) as e:
startGame(owner) startGame(owner)
assert "Status is not ok" in str(e.value)
def test_that_non_owners_cant_start_a_game(): def test_that_non_owners_cant_start_a_game():
with pytest.raises(Exception) as e: owner = User("neosteopathie")
owner = User("neosteopathie") notOwner = User("neorphelin")
notOwner = User("neorphelin") game_id = createGame(owner)
game_id = createGame(owner) joinGame(notOwner,game_id)
joinGame(notOwner,game_id) with pytest.raises(TestException) as e:
assert startGame(notOwner) == False startGame(notOwner)
assert "Status is not ok" in str(e.value)

View File

@ -50,13 +50,21 @@ class Game:
self.game_id = None self.game_id = None
self.owner = None self.owner = None
self.members = [] self.members = []
self.has_started = False
def set_owner(self, username): def set_owner(self, username):
self.owner = Member(username) self.owner = Member(username)
self.members.append(self.owner) self.members.append(self.owner)
return self.owner return self.owner
def get_member(self, username):
for member in self.members:
if member.username == username:
return member
def add_member(self, username): def add_member(self, username):
if self.get_member(username):
return None
member = Member(username) member = Member(username)
self.members.append(member) self.members.append(member)
return member return member

View File

@ -2,6 +2,7 @@ import flask
import truthseeker import truthseeker
from truthseeker.logic import game_logic from truthseeker.logic import game_logic
from truthseeker.utils import check_username
routes_api = flask.Blueprint("api", __name__) routes_api = flask.Blueprint("api", __name__)
@ -10,11 +11,12 @@ routes_api = flask.Blueprint("api", __name__)
def create_game(): def create_game():
username = flask.request.values.get("username") username = flask.request.values.get("username")
if username==None: if username==None:
return {"status": "error, username not set"} return {"error": 1, "msg": "username not set"}
if not check_username(username):
return {"error": 1, "msg": "invalid username"}
response = {} response = {}
response["status"] = "ok" response["error"] = 0
game = game_logic.create_game(owner=username) game = game_logic.create_game(owner=username)
response["game_id"] = game.game_id response["game_id"] = game.game_id
@ -29,30 +31,40 @@ def join_game():
game_id = flask.request.values.get("game_id") game_id = flask.request.values.get("game_id")
username = flask.request.values.get("username") username = flask.request.values.get("username")
if game_id==None or username==None: if game_id==None or username==None:
return {"status": "error, username or game id not set"} return {"error": 1, "msg": "username or game id not set"}
if not check_username(username):
return {"error": 1, "msg": "invalid username"}
game = game_logic.get_game(game_id) game = game_logic.get_game(game_id)
if game == None: if game == None:
return {"status": "error, game does not exist"} return {"error": 1, "msg": "game does not exist"}
if not game.add_member(username):
game.add_member(username) return {"error": 1, "msg": f"Username '{username}' already used in game {game.game_id}"}
flask.session["game_id"] = game.game_id flask.session["game_id"] = game.game_id
flask.session["is_owner"] = False flask.session["is_owner"] = False
flask.session["username"] = username flask.session["username"] = username
response = {} return {"error": 0}
response["status"] = "ok"
return response
@routes_api.route("/startGame", methods=["GET", "POST"]) @routes_api.route("/startGame", methods=["GET", "POST"])
def start_game(): def start_game():
if not flask.session: if not flask.session:
return {"status": "No session"} return {"error": 1, "msg": "No session"}
if not flask.session["is_owner"]: if not flask.session["is_owner"]:
return {"status": "Error, you are not the owner of this game"} return {"error": 1, "msg": "you are not the owner of this game"}
if game_logic.get_game(flask.session["game_id"]) == None:
return {"status": "Error, this game doesn't exist"}
return {"status": "ok"} game = game_logic.get_game(flask.session["game_id"])
if game == None:
return {"error": 1, "msg": "this game doesn't exist"}
print(game.has_started)
if game.has_started:
return {"error": 1, "msg": "this game is already started"}
game.has_started = True
return {"error": 0}

11
truthseeker/utils.py Normal file
View File

@ -0,0 +1,11 @@
def check_username(username):
if not username:
return False
if not username.isalnum():
return False
if not username == username.strip():
return False
if not len(username) < 16:
return False
return True