How do i do unit tests in python? - python

I have a simple program for traslating morse code back and forth as a school project and part of it is also writting unit tests. I ve tried for multiple hours but was not succesful at all
dictionary={'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.','F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-','L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-','R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--','X':'-..-', 'Y':'-.--', 'Z':'--..'}
dictionary2={'.-':'A','-...':'B','-.-.':'C','-..':'D', '.':'E','..-.':'F','--.':'G','....':'H',
'..':'I','.---':'J', '-.-':'K','.-..':'L', '--':'M', '-.':'N',
'---':'O', '.--.':'P', '--.-':'Q','.-.':'R', '...':'S', '-':'T',
'..-':'U', '...-':'V', '.--':'W','-..-':'X', '-.--':'Y', '--..':'Z', '':' '}
def coding(s):
void=""
for i in s: #indexing
if i != ' ':
void+=dictionary[i]+' '
else:
void +=' '
print(void)
def decoding(s):
void = ""
splitstring=s.split(" ")
splitstring = s.split(" ")#splitting by spaces
#splitstring=splitstring.remove('')
for i in splitstring: #indexing
void += dictionary2[i]
print(void)
def selection(f):
f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
return f
c = 1
d = 0
while(c!="0"):
d =selection(d)
a=input("ZADEJ TEXT NA ŠIFROVÁNÍ: ")
a=a.upper()
startUp="" # not being used but program cant be ran without it for some reason
if d==1: # translating to morse code
coding(a)
else: # translating from morse code
decoding(a)
c = input(("POKUD CHCTE PROGRAM UKONČIT, ZADEJTE 0 || PRO POKRAČOVÁNÍ ZADEJTE LIBOVOLNÝ ZNAK : "))
this is what i ve tried:
import pytest
from example import coding
from example import decoding
def test_coding():
assert coding('HELLO') == '.... . .-.. .-.. --- '
assert coding('WORLD') == '.-- .-. .. -. ..-. '
assert coding('HELLO WORLD') == '.... . .-.. .-.. --- .-- .-. .. -. ..-. '
test_coding()
#To write unit tests for the decoding() function, we can test that it decodes strings correctly by comparing the output of the function with the expected result. For example:
def test_decoding():
assert decoding('.... . .-.. .-.. --- ') == 'HELLO'
assert decoding('.-- .-. .. -. ..-. ') == 'WORLD'
assert decoding('.... . .-.. .-.. --- .-- .-. .. -. ..-. ') == 'HELLO WORLD'
test_decoding()
My teacher wants those tests to be ran with this command:
py.exe -m pytest --cov=. --cov-fail-under=66
in command block, it has to reach at least 66% success rate.
thus far i ve always ended up with this result:
=========================================================================================================== test session starts ============================================================================================================
platform win32 -- Python 3.9.6, pytest-7.2.0, pluggy-1.0.0
rootdir: C:\Users\ash31\OneDrive\Plocha\AP1VS-final-project
plugins: cov-4.0.0
collected 0 items / 1 error
================================================================================================================== ERRORS ==================================================================================================================
_____________________________________________________________________________________________________ ERROR collecting example_test.py _____________________________________________________________________________________________________
example_test.py:1: in <module>
from example import coding
example.py:51: in <module>
d =selection(d)
example.py:43: in selection
f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\_pytest\capture.py:192: in read
raise OSError(
E OSError: pytest: reading from stdin while output is captured! Consider using `-s`.
------------------------------------------------------------------------------------------------------------- Captured stdout --------------------------------------------------------------------------------------------------------------
1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY
----------- coverage: platform win32, python 3.9.6-final-0 -----------
Name Stmts Miss Cover
-------------------------------------
example.py 32 22 31%
example_test.py 24 23 4%
-------------------------------------
TOTAL 56 45 20%
FAIL Required test coverage of 66% not reached. Total coverage: 19.64%
========================================================================================================= short test summary info ==========================================================================================================
ERROR example_test.py - OSError: pytest: reading from stdin while output is captured! Consider using `-s`.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================================= 1 error in 0.46s =============================================================================================================

Related

pytest if else check

I am trying to learn pytest and testing my knowledge on the below code.
src.py
def a(s):
if s == 1:
return True
if s == 2:
return False
return 3
def abc(u):
if u ==1:
if a(u):
return 1
else:
if a(u):
return 2
else:
return 3
and this is my test file:
import pytest
import src
#pytest.mark.parametrize("input_data, expected", [(1,1), (2,2), (3,2)])
def test_abc(input_data, expected, mocker):
s = mocker.patch('src.a', side_effect=[True, False])
assert src.abc(input_data) == expected
s.assert_called_once_with(input_data)
#pytest.mark.parametrize("input_data, expected", [(1,True), (2,False), (3,3)])
def test_a(input_data, expected,):
assert src.a(input_data) == expected
Testing the code returns all passed, but the coverage reports that the line 16 is not being tested:
% pytest -v --cov=. . --cov-report term-missing
==================================================================== test session starts ====================================================================
platform darwin -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0 -- /Users/tomhanks/.pyenv/versions/3.10.4/bin/python3.10
cachedir: .pytest_cache
rootdir: /Users/tomhanks/projects/pytest
plugins: mock-3.7.0, cov-3.0.0
collected 6 items
test_me.py::test_abc[1-1] PASSED [ 16%]
test_me.py::test_abc[2-2] PASSED [ 33%]
test_me.py::test_abc[3-2] PASSED [ 50%]
test_me.py::test_a[1-True] PASSED [ 66%]
test_me.py::test_a[2-False] PASSED [ 83%]
test_me.py::test_a[3-3] PASSED [100%]
---------- coverage: platform darwin, python 3.10.4-final-0 ----------
Name Stmts Miss Cover Missing
------------------------------------------
src.py 13 1 92% 16
test_me.py 10 0 100%
------------------------------------------
TOTAL 23 1 96%
===================================================================== 6 passed in 0.07s =====================================================================
Can somebody please help me understand why the line 16 is not being tested?
Thanks in advance!

Error when trying to print string with multiple lines

I'm trying to make a tic tac toe game in Python but whenever I try to print the board, I get a weird error. Here is my code:
import os
from colorama import Fore
board = " a b c\n | | \n1 - | - | - \n _____|_____|_____\n | | \n2 - | - | - \n _____|_____|_____\n | | \n3 - | - | - \n | | "
def board():
print(board)
board()
And this is the error:
 SIGQUIT: quit
PC=0x7f1a62b22792 m=0 sigcode=128
signal arrived during cgo execution
goroutine 1 [syscall, locked to thread]:
runtime.cgocall(0x4bb660, 0xc000066d90)
runtime/cgocall.go:156 +0x5c fp=0xc000066d68 sp=0xc000066d30 pc=0x40651c
main._Cfunc_PyRun_InteractiveLoopFlags(0x7f1a62be9800, 0x55555691b800, 0x0)
_cgo_gotypes.go:418 +0x4c fp=0xc000066d90 sp=0xc000066d68 pc=0x4b8e4c
main.Python.REPL.func2(0x55555691b800)
github.com/replit/prybar/languages/python3/main.go:122 +0x66 fp=0xc000066dd0 sp=0xc000066d90 pc=0x4bacc6
main.Python.REPL({})
github.com/replit/prybar/languages/python3/main.go:122 +0x99 fp=0xc000066e10 sp=0xc000066dd0 pc=0x4bac19
main.(*Python).REPL(0x5d56d0)
<autogenerated>:1 +0x2a fp=0xc000066e20 sp=0xc000066e10 pc=0x4bb36a
github.com/replit/prybar/utils.Language.REPL({{0x5075d0, 0x5d56d0}, {0x7ffd00c3ac79, 0x4e1680}})
github.com/replit/prybar/utils/language.go:100 +0x5d fp=0xc000066e78 sp=0xc000066e20 pc=0x4b825d
github.com/replit/prybar/utils.DoCli({0x5075d0, 0x5d56d0})
github.com/replit/prybar/utils/utils.go:77 +0x3d7 fp=0xc000066f60 sp=0xc000066e78 pc=0x4b8a97
main.main()
github.com/replit/prybar/languages/python3/generated_launch.go:7 +0x27 fp=0xc000066f80 sp=0xc000066f60 pc=0x4b8bc7
<function board at 0x7f5f840e2280>
I haven't seen a error like this before and am wondering what it means and how to fix it? Thanks for help!
The problem is that you are naming everything "board"
When you do "def board()" after "board = ..." you are redefining board to be a function and no longer a string.
The error you are getting is due to your editor somehow not supporting printing functions

Python opts get empty values

I'm trying to work with opts but cannot get it to work in other PC because arguments it's always empty. Below is my code.
import getopt
import sys
try:
print getopt.getopt(sys.argv[1:], "f::c::")
opts, args = getopt.getopt(sys.argv[1:], "f::c::")
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
sys.exit(2)
print opts
print args
funcion = None
tipo = None
for opt, arg in opts:
if opt in ('-f'):
funcion = arg
if opt in ('-c'):
tipo = arg
print funcion
print tipo
usage test:
python test.py –f import_dbs –c 1
PC A result:
([('-f', 'imports'), ('-c', '1')], [])
[('-f', 'imports'), ('-c', '1')]
[]
imports
1
PC B result:
([], ['\x96f', 'import_dbs', '\x96c', '1'])
[]
['\x96f', 'import_dbs', '\x96c', '1']
None
None
the problem is with your cli command, not your code. you have dashes (or some sort of unicode) instead of hyphens
$ python test.py –f import_dbs –c 1
None
None
$ python test.py -f import_dbs –c 1
import_dbs
None
$ python test.py -f import_dbs -c 1
import_dbs
1
$ echo "python test.py –f import_dbs –c 1" | od -c
0000000 p y t h o n t e s t . p y –
0000020 ** ** f i m p o r t _ d b s –
0000040 ** ** c 1 \n
0000046
$ echo "python test.py -f import_dbs -c 1" | od -c
0000000 p y t h o n t e s t . p y -
0000020 f i m p o r t _ d b s - c
0000040 1 \n
0000042
probably caused by cutting and pasting or weird keyboard mapping.

Why won't my code run?

Ascii credits - http://www.chris.com/ascii
The code won't run in pyscripter for some reason only showing two chevron prompts please help me out? Thanks. Also if you think you find any problems(bugs) etc. with the code. feel free to correct me or correct it yourself,thanks.
import random
import time
playagain = True
def intro():
print('You and your brave behind stare at the large dark forest infront of you.')
time.sleep(2)
print()
print('Instead of ignoring the darkness and spookiness of the forest you decide to enter anyways.')
time.sleep(2)
print()
print('You do not worry because you are a brave archer heralding a bow with deadly tipped arrows.')
print()
print('What is your name brave Archer')
print()
choice = input()
print('That is a name which brings fear, ' + choice)
print()
def monsters():
monster = ['''oo88888888boo
`""88888888888bo
""888; `"Y888o
Y88; "Y88.
"88. `88b. ,
`Yb `888. :8b
Yb , `888. 88b
Y. ` `"88. Y8"8.
Y. `. b ``8b :8 Y8.
,oooooooo Yo :.`b`b`8; 8 8b
,ood8P""""""""88888oo 8b Y.:b:b:8;,8 ,:8.
,od88888bo ` ,o. """888o`8b`8 Y.8.88d8 : 8;
"""""""""""8oo`,. 'oo. ""888b8b:8db8888 d :8 :;
d8888boP , "Y88o. ""Y8888888888 8 d8.88
o""""888888o``o'"88bood8888888888:8,;8888
o" ""8888888o."88888888" oooo `888d888:8
d' ,o8888888P88od88P""' ,d8888; Y888888:8
,8' ood88888,dP"88 :888888 :88888;d;
8' ,o88""8888`8P `" 888888P 8888d;8;
d;,o8P" ,d888'oP' "8888" d88888boo
8,88' ,8888'88 `' ,o8; "" Y88888888oooo.
:88' ,8888'dP,88o :; d88P oooo88d888888888bo.
`" ,8888;,;:88888. d8. :8P' ""' :8888888888ooo
,88888 8,88. :88; 88; ood" 88888888888P"Y;
oP d88;d;d888od"Y8 8; "" :8P""Y88PYb8 :
:P'd888`8'8b ""Y88. 8' `" `8" YP 8
,P .:Y8Pd8,8Y88o. :; `" o8 d;
,8'','8888;:8o """Y8 ooood88888oooo. o dP
8P ,d88'8;:8"888oooo8; ,o888888888888888888boo `Y8oo. dP
:8bd88888 8':8ooo. ""Yb odP"" """888888888bo8P""'o8"
"""""8888 8 :8888888o. 8oooo888oooooooooo. Y8888888888oo8"
d8888 Y :bo `""""888P""" ""Ybo. `"8888888""
,8`Y88.: :8"Y88oooooooo88. `Ybo Y8"
dP'd88;:; 8o `""Y8b `"b. dP
88`8:8;:; 88888booooood888. `8. 8'
:8P:'Y88:b 8P `8b `8d8'
88 ',88888 Y8888ooooooP""""Yb `"
,8; o8888bY;8Yb ' ooo88b
:8o8":;888'8;88bo,od8` '`'`' Ybo
d8" d;888bP;o'` ,.:o:'`"P o
"' 8'8888d8b,;odP8;dP'` o:;`'8 :o '
8 :8P8'88o`8P'' ooo' ,oo" d8.dboo
,8 :`d88b,88od8888P"' oo"" ,'" dP"88888
:P 88888;8b 888; oo8"' ,P' ,8' d'88"8
d;,dY88888.Y. Y8888"" odP' ,d" ,d'dP ,P
8bP' Y8Y888d8o `Y8; ood8P' ,dP o8':P :;
,P" :8YY;88b"b Y8888P" o'" o8P ,P 8 -hrr-
`8d:`888b`bo `8b ,o8" ,dP' ,P :;
8;:dP88888Yb Y888; d8; ,P 8
8;:8 :8888b88. `Y8boo8P' ,P :;
8b8' `88:;Y88"b. `Y888 ,P 8
88' Y88':88b."8o `"8b.oP 8'
"' :8Y :88888o"8o :88o. ,8'
8: 88;8Y88b88bod8"Y8oo8P
8.d':b8`8:P`"8888o. :8P
88' Yd 88' `"88888"
:8' `8 dP """'
`' 8o8
88''', ''' ___
`-._~-. / /_ "~o\ :Y
\ \ / : \~x. ` ')
] Y / | Y< ~-.__j
/ ! _.--~T : l l< /.-~
/ / ____.--~ . ` l /~\ \<|Y
/ / .-~~" /| . ',-~\ \L|
/ / / .^ \ Y~Y \.^>/l_ "--'
/ Y .-"( . l__ j_j l_/ /~_.-~ .
Y l / \ ) ~~~." / `/"~ / \.__/l_
| \ _.-" ~-{__ l : l._Z~-.___.--~
| ~---~ / ~~"---\_ ' __[>
l . _.^ ___ _>-y~
\ \ . .-~ .-~ ~>--" /
\ ~---" / ./ _.-'
"-.,_____.,_ _.--~\ _.-~
~~ ( _}
`. ~(
) \
/,`--'~\--''' , '''
_ ___ /^^\ /^\ /^^\_
_ _#)#) \ ,,/ '` ~ `'~~ ', `\.
_/o\_ _ _ _/~`.`...'~\ ./~~..,'`','',.,' ' ~:
/ `,'.~,~.~ . , . , ~|, ,/ .,' , ,. .. ,,. `, ~\_
( ' _' _ '_` _ ' . , `\_/ .' ..' ' ` ` `.. `, \_
~V~ V~ V~ V~ ~\ ` ' . ' , ' .,.,''`.,.''`.,.``. ', \_
_/\ /\ /\ /\_/, . ' , `_/~\_ .' .,. ,, , _/~\_ `. `. '., \_
< ~ ~ '~`'~'`, ., . `_: ::: \_ ' `_/ ::: \_ `.,' . ', \_
\ ' `_ '`_ _ ',/ _::_::_ \ _ _/ _::_::_ \ `.,'.,`., \-,-,-,_,_,
`'~~ `'~~ `'~~ `'~~ \(_)(_)(_)/ `~~' \(_)(_)(_)/ ~'`\_.._,._,'_;_;_;_;_; '''
, ''' |\___/|
(,\ /,)\
/ / \
(#_^_#)/ \
W//W_/ \
(//) | \
(/ /) _|_ / ) \
(// /) '/,_ _ _/ (~^-.
(( // )) ,-{ _ `.
(( /// )) '/\ / |
(( ///)) `. { }
((/ )) .----~-.\ \-'
///.----..> \
///-._ _ _ _} '''
, '''
/ o o \
/ \ / \
/ )-"-( \
/ ( 6 6 ) \
/ \ " / \
/ )=( \
/ o .--"-"--. o \
/ I / - - \ I \
.--( (_}y/\ /\y{_) )--.
( ".___l\/__\_____/__\/l___," )
\ /
"-._ o O o O o O o _,-"
`--Y--.___________.--Y--'
|==.___________.==| ''']
print('You walk through the forest slowly...')
time.sleep(2)
print('You hear a crack as if a twig broke..')
time.sleep(2)
print('The creature leaps out from the shadows!')
time.sleep(5)
print()
print(random.choice(monster))
print('You must engage the creature!')
def battle():
attack = [poison, fire, lightning, ice, greatbow]
gold = [1,2,3]
print('You ready your bow as you choose which tipped arrow to use embued with magic..')
time.sleep(2)
print('You strung your bow with the ' + random.choice(attack) + ' arrow')
time.sleep(3)
print('You take down the foe as he slowly tumbles to the ground!')
time.sleep(2)
print('The bigger they are the harder they fall')
time.sleep(3)
print('Would you like to enter deeper into the forest or flee while you can, you collected ' + gold + ' gold stacks this time around')
playagain = input()
while playagain == 'yes':
return intro
return monsters
return battle
else: exit()
Make a list into string or some data type according to your need. For-example
attack = ["poison", "fire", "lightning", "ice", "greatbow"]
Secondly change the int gold to str in this line given below:
print('Would you like to enter deeper into the forest or flee while you can, you collected ' + str(gold) + ' gold stacks this time around')
I am using python2.7 , change also 'yes' into "yes"
playagain = raw_input('Choose a number')
while playagain == "yes":
return intro
return monsters
return battle
else: exit()
if __name__ == "__main__":
battle()
I don't know which one of method you want to call but I called battle() method and it run fine.
Right first of all change all the input to raw_input. Also I guess the idea is to start from the intro function, then move to the monsters function and then to the battle function. Although you have defined them fine, you do not call them anywhere. What you could do for example is call the monsters function from the intro function, and then the battle function from the monsters function similarly

Splitting a string for printing

I need to print some headers around some strings, you can see it working fine here, although if the string is really long I need to split it then print a much longer header.
+===================================================+
| Running: sdt_test |
| Skipping:inquiry/"Inq VPD C0" mem/"Maint In Cmnd" |
+===================================================+
sh: /net/flanders/export/ws/ned/proto/bin/sdt_test: No such file or directory
+=====================+
| Running: dtd_tester |
+=====================+
sh: /net/flanders/export/ws/ned/proto/bin/dtd_tester: No such file or directory
+===============+
| Running: pssm |
+===============+
sh: /net/flanders/export/ws/ned/proto/bin/pssm: No such file or directory
+==============+
| Running: psm |
+==============+
sh: /net/flanders/export/ws/ned/proto/bin/psm: No such file or directory
+===============================================================================================================================================================================================================================================================================================================================================+
| Running: ssm |
| Skipping:"Secondary Subset Manager Tests"/"SSSM_3 Multi Sequence" "Secondary Subset Manager Tests"/"SSSM_2 Steady State" "Secondary Subset Manager Tests"/"SSSM_4 Test Abort" "Secondary Subset Manager Tests"/"SSSM_6 Test extend" "Secondary Subset Manager Tests"/"SSSM_9 exceptions" "Secondary Subset Manager Tests"/"SSSM_11 failed io" |
+===============================================================================================================================================================================================================================================================================================================================================+
It appears fine there, although the SSM test, I would like split up on a certain amount of characters, maybe 100 or just on the whitespace between suites.
I'm really not too sure on how to do this, this is the code that currently does it.
#calculate lengths to make sure header is correct length
l1 = len(x)
l2 = len(y)
skip = False
if 'disable=' in test and 'disable="*"' not in test:
skip = True
#if entire test suite is to be disabled or not run
if disable:
headerBreak ="+" + "="*(l1+12) + "+"
print headerBreak
print "| Skipping: %s |" % x
#if the test suite will be executed
else:
if skip == False:
l2 = 0
headerBreak = "+" + "="*(max(l1,l2)+11) + "+"
print headerBreak
print "| Running: %s" % x, ' '*(l2-l1)+ '|'
#if some suites are disabled but some are still running
if skip:
print "| Skipping:%s |" % y
print headerBreak
sys.stdout.flush()
You can use the textwrap module to simplify this
For example if the max width was 44
>>> max_width = 44
>>> header='''Skipping:"Secondary Subset Manager Tests"/"SSSM_3 Multi Sequence" "Secondary Subset Manager Tests"/"SSSM_2 Steady State" "Secondary Subset Manager Tests"/"SSSM_4 Test Abort" "Secondary Subset Manager Tests"/"SSSM_6 Test extend" "Secondary Subset Manager Tests"/"SSSM_9 exceptions" "Secondary Subset Manager Tests"/"SSSM_11 failed io"'''
>>> h = ["Running: ssm"] + textwrap.wrap(header, width=max_width-4)
>>> maxh = len(max(h, key=len))
>>> print "+=" + "="*maxh + "=+"
+==========================================+
>>> for i in h:
... print "| " + i.ljust(maxh) + " |"...
| Running: ssm |
| Skipping:"Secondary Subset Manager |
| Tests"/"SSSM_3 Multi Sequence" |
| "Secondary Subset Manager Tests"/"SSSM_2 |
| Steady State" "Secondary Subset Manager |
| Tests"/"SSSM_4 Test Abort" "Secondary |
| Subset Manager Tests"/"SSSM_6 Test |
| extend" "Secondary Subset Manager |
| Tests"/"SSSM_9 exceptions" "Secondary |
| Subset Manager Tests"/"SSSM_11 failed |
| io" |
>>> print "+=" + "="*maxh + "=+"
+==========================================+

Categories

Resources