Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ckooistra #2257

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Binary file added .coverage
Binary file not shown.
Binary file added Coverage_statements_power.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Industrial_developed_hangman/.coverage
Binary file not shown.
53 changes: 53 additions & 0 deletions Industrial_developed_hangman/covreport_hangman.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

## Output of coverage report BEFORE added tests
Name Stmts Miss Cover Missing
--------------------------------------------------------------
src/hangman/__init__.py 0 0 100%
src/hangman/main.py 99 7 93% 82-84, 126, 168, 181-182
tests/__init__.py 0 0 100%
tests/test_hangman/__init__.py 0 0 100%
--------------------------------------------------------------
TOTAL 99 7 93%


## Output of function to identify conditional branches (before coverage test)
--------------------------------------------------------------
try_block: Reached
except_connection_error: Not Reached
status_code_check: Reached
return_statement: Reached
raise_runtime_error: Not Reached
--------------------------------------------------------------


## Included test function (in test_main.py)
def test_parse_word_from_site_err() -> None:
with requests_mock.Mocker() as mock:
mock.get('https://random-word-api.herokuapp.com/word', status_code=404)
with pytest.raises(RuntimeError):
parse_word_from_site()
print_coverage()


## Output of coverage report AFTER added tests
Name Stmts Miss Cover Missing
---------------------------------------------------------------
src/hangman/__init__.py 0 0 100%
src/hangman/main.py 102 4 96% 126, 168, 181-182
tests/__init__.py 0 0 100%
tests/test_hangman/__init__.py 0 0 100%
tests/test_hangman/test_main.py 76 0 100%
---------------------------------------------------------------
TOTAL 178 4 98%


## Output of function to identify conditional branches (after coverage test)
---------------------------------------------------------------
try_block: Reached
except_connection_error: Reached
status_code_check: Reached
return_statement: Reached
raise_runtime_error: Reached
---------------------------------------------------------------

# Stan.
5 changes: 5 additions & 0 deletions Industrial_developed_hangman/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
try_block: Reached
except_connection_error: Reached
status_code_check: Reached
return_statement: Reached
raise_runtime_error: Reached
43 changes: 33 additions & 10 deletions Industrial_developed_hangman/src/hangman/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import time
from enum import Enum
from pathlib import Path
from typing import Callable, List
from typing import Callable, List, Dict

import requests
from colorama import Fore, Style
Expand All @@ -14,6 +14,14 @@
data_path = Path(__file__).parent.parent.parent / 'Data'
year = 4800566455

# Data structure to hold coverage information
coverage = {
"try_block": False,
"except_connection_error": False,
"status_code_check": False,
"return_statement": False,
"raise_runtime_error": False
}

class Source(Enum):
"""Enum that represents switch between local and web word parsing."""
Expand Down Expand Up @@ -60,23 +68,28 @@ def parse_word_from_local(choice_function: Callable[[List[str]], str] = random.c


def parse_word_from_site(url: str = 'https://random-word-api.herokuapp.com/word') -> str:
# noqa: DAR201
"""
Parse word from website.

:param url: url that word will be parsed from.
:return Optional[str]: string that contains the word.
:raises ConnectionError: no connection to the internet.
:raises RuntimeError: something go wrong with getting the word from site.
:param url: URL that word will be parsed from.
:return: string that contains the word.
:raises requests.exceptions.ConnectionError: no connection to the internet.
:raises RuntimeError: something went wrong with getting the word from the site.
"""
try:
response: requests.Response = requests.get(url, timeout=request_timeout)
except ConnectionError:
raise ConnectionError('There is no connection to the internet')
coverage["try_block"] = True # Added line: marking the try block as reached
except requests.exceptions.ConnectionError:
coverage["except_connection_error"] = True # Added line: marking the except block as reached
raise requests.exceptions.ConnectionError('There is no connection to the internet')

if response.status_code == success_code:
coverage["status_code_check"] = True # Added line: marking the status code check as reached
coverage["return_statement"] = True # Added line: marking the return statement as reached
return json.loads(response.content.decode())[0]
raise RuntimeError('Something go wrong with getting the word from site')


coverage["raise_runtime_error"] = True # Added line: marking the raise runtime error as reached
raise RuntimeError('Something went wrong with getting the word from site')

class MainProcess(object):
"""Manages game process."""
Expand Down Expand Up @@ -167,3 +180,13 @@ def start_game(self) -> None:
if __name__ == '__main__':
main_process = MainProcess(Source(1), print, input, random.choice)
main_process.start_game()

# Function to print and save coverage information
def print_coverage() -> None:
with open("output.txt", "w") as f:
for statement, reached in coverage.items():
output = f"{statement}: {'Reached' if reached else 'Not Reached'}"
print(output)
f.write(output + "\n")

print_coverage()
33 changes: 24 additions & 9 deletions Industrial_developed_hangman/tests/test_hangman/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,27 @@
from typing import Callable, List

import pytest
import requests
import requests_mock

from src.hangman.main import (
MainProcess,
Source,
parse_word_from_local,
parse_word_from_site,
print_coverage, # Ensure this is imported
)


class FkPrint(object):
class FkPrint:
def __init__(self) -> None:
self.container: List[str] = []

def __call__(self, value_to_print: str) -> None:
self.container.append(str(value_to_print))


class FkInput(object):
class FkInput:
def __init__(self, values_to_input: List[str]) -> None:
self.values_to_input: List[str] = values_to_input

Expand All @@ -31,7 +33,7 @@ def __call__(self) -> str:

@pytest.fixture
def choice_fn() -> Callable:
return lambda array: array[0] # noqa: E731
return lambda array: array[0]


def test_parse_word_from_local() -> None:
Expand All @@ -52,17 +54,30 @@ def test_parse_word_from_local_error() -> None:
@pytest.mark.internet_required
def test_parse_word_from_site() -> None:
assert isinstance(parse_word_from_site(), str)
print_coverage()


def test_parse_word_from_site_no_internet() -> None:
with requests_mock.Mocker() as mock:
mock.get('https://random-word-api.herokuapp.com/word', text='["some text"]')
assert parse_word_from_site() == 'some text'
mock.get('https://random-word-api.herokuapp.com/word', exc=requests.exceptions.ConnectionError)
with pytest.raises(requests.exceptions.ConnectionError):
parse_word_from_site()
print_coverage()


def test_parse_word_from_site_success() -> None:
with requests_mock.Mocker() as mock:
mock.get('https://random-word-api.herokuapp.com/word', text='["some_text"]')
assert parse_word_from_site() == 'some_text'
print_coverage()


def test_parse_word_from_site_err() -> None:
with pytest.raises(RuntimeError):
parse_word_from_site(url='https://www.google.com/dsfsdfds/sdfsdf/sdfds')
with requests_mock.Mocker() as mock:
mock.get('https://random-word-api.herokuapp.com/word', status_code=404)
with pytest.raises(RuntimeError):
parse_word_from_site()
print_coverage()


def test_get_word(choice_fn: Callable) -> None:
Expand All @@ -83,7 +98,7 @@ def test_start_game_win(choice_fn: Callable) -> None:
assert 'YOU WON' in fk_print.container[-1]


@pytest.mark.parametrize('input_str', [[letter] * 10 for letter in 'qwertyuiopasdfghjklzxcvbnm']) # noqa: WPS435
@pytest.mark.parametrize('input_str', [[letter] * 10 for letter in 'qwertyuiopasdfghjklzxcvbnm'])
def test_start_game_loose(input_str: List[str], choice_fn: Callable) -> None:
fk_print = FkPrint()
fk_input = FkInput(input_str)
Expand All @@ -97,7 +112,7 @@ def test_start_game_loose(input_str: List[str], choice_fn: Callable) -> None:
def test_wow_year(freezer, choice_fn: Callable) -> None:
freezer.move_to('2135-10-17')
fk_print = FkPrint()
fk_input = FkInput(['none'] * 100) # noqa: WPS435
fk_input = FkInput(['none'] * 100)
main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn)

main_process.start_game()
Expand Down
Binary file added PongPong_Game/.coverage
Binary file not shown.
8 changes: 8 additions & 0 deletions PongPong_Game/coverage
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
pong/ball.py/BallObject/update.if: Covered
pong/ball.py/BallObject/update.elif: Covered
pong/ball.py/BallObject/update.elif2: Covered
pong/ball.py/BallObject/update.else: Covered
pong/paddle.py/Paddle/update.if1: Covered
pong/paddle.py/Paddle/update.elif1: Covered
pong/paddle.py/Paddle/update.if2: Covered
pong/paddle.py/Paddle/update.elif2: Covered
10 changes: 9 additions & 1 deletion PongPong_Game/pong/ball.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pyglet
import random
from typing import Tuple

from track import update_coverage

class BallObject(pyglet.shapes.Circle):
def __init__(self, *args, **kwargs):
Expand All @@ -29,13 +29,21 @@ def update(self, win_size: Tuple, border: Tuple, other_object, dt) -> None:
newy = self.y + self.velocity_y

if newx < border + self.radius or newx > win_size[0] - border - self.radius:
update_coverage("pong/ball.py/BallObject/update.if")

self.velocity_x = -(self.velocity_x / abs(self.velocity_x)) * rn
elif newy > win_size[1] - border - self.radius:
update_coverage("pong/ball.py/BallObject/update.elif")

self.velocity_y = -(self.velocity_y / abs(self.velocity_y)) * rn
elif (newy - self.radius < other_object.height) and (
other_object.x <= newx <= other_object.rightx
):
update_coverage("pong/ball.py/BallObject/update.elif2")

self.velocity_y = -(self.velocity_y / abs(self.velocity_y)) * rn
else:
update_coverage("pong/ball.py/BallObject/update.else")

self.x = newx
self.y = newy
9 changes: 9 additions & 0 deletions PongPong_Game/pong/paddle.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pyglet
from pyglet.window import key
from typing import Tuple
from track import update_coverage


class Paddle(pyglet.shapes.Rectangle):
Expand All @@ -20,15 +21,23 @@ def update(self, win_size: Tuple, border: float, other_object, dt):
newrx = self.x + self.acc_right

if self.key_handler[key.LEFT]:
update_coverage("pong/paddle.py/Paddle/update.if1")

self.x = newlx
elif self.key_handler[key.RIGHT]:
update_coverage("pong/paddle.py/Paddle/update.elif1")

self.x = newrx

self.rightx = self.x + self.width

if self.x < border:
update_coverage("pong/paddle.py/Paddle/update.if2")

self.x = border
self.rightx = self.x + self.width
elif self.rightx > win_size[0] - border:
update_coverage("pong/paddle.py/Paddle/update.elif2")

self.x = win_size[0] - border - self.width
self.rightx = self.x + self.width
4 changes: 4 additions & 0 deletions PongPong_Game/pongpong.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pyglet
from pong import load
from track import update_coverage, print_coverage, write_coverage_to_file

# Variables, Considering a vertical oriented window for game
WIDTH = 600 # Game Window Width
Expand Down Expand Up @@ -58,3 +59,6 @@ def update(dt):
if __name__ == "__main__":
pyglet.clock.schedule_interval(update, 1 / 120.0)
pyglet.app.run()

print_coverage()
write_coverage_to_file("coverage")
35 changes: 35 additions & 0 deletions PongPong_Game/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from pong.ball import BallObject
from pong.paddle import Paddle
from pyglet.window import key
from unittest.mock import MagicMock
import pytest

def test_ball_update_elif():
ball = BallObject(x=50, y=95, radius=10)
ball.velocity_x = 0
ball.velocity_y = 10
win_size = (100, 100)
border = 5

other_object = MagicMock()
other_object.height = 10
other_object.x = 0
other_object.rightx = 0

ball.update(win_size=win_size, border=border, other_object=other_object, dt=0.1)
from track import coverage_dict
assert coverage_dict["pong/ball.py/BallObject/update.elif"]

def test_paddle_update_elif2():
paddle = Paddle(x=90, y=50, width=10, height=10)
paddle.key_handler = MagicMock()
paddle.key_handler[key.LEFT] = False
paddle.key_handler[key.RIGHT] = False
paddle.acc_right = 0
paddle.acc_left = 0
win_size = (100, 100)
border = 5

paddle.update(win_size=win_size, border=border, other_object=MagicMock(), dt=0.1)
from track import coverage_dict
assert coverage_dict["pong/paddle.py/Paddle/update.elif2"]
24 changes: 24 additions & 0 deletions PongPong_Game/track.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#track.py
coverage_dict = {
"pong/ball.py/BallObject/update.if": False,
"pong/ball.py/BallObject/update.elif": False,
"pong/ball.py/BallObject/update.elif2": False,
"pong/ball.py/BallObject/update.else": False,
"pong/paddle.py/Paddle/update.if1": False,
"pong/paddle.py/Paddle/update.elif1": False,
"pong/paddle.py/Paddle/update.if2": False,
"pong/paddle.py/Paddle/update.elif2": False,
}

def update_coverage(key):
if key in coverage_dict:
coverage_dict[key] = True

def print_coverage():
for key, value in coverage_dict.items():
print(f"{key}: {'Covered' if value else 'Not Covered'}")

def write_coverage_to_file(filename):
with open(filename, 'w') as file:
for key, value in coverage_dict.items():
file.write(f"{key}: {'Covered' if value else 'Not Covered'}\n")
Loading