Getting unittest assert.Equal returns failure when it shouldn't - python

I am very new to python and have been tasked with using unittest for my code,
my code is as follows:
import platform
import os
OpSys=platform.system()
def clear ():
if (OpSys=="Windows"):
os.system("cls")
else:
os.system("clear")
def ShowPlaca(type):
if (type!=""):
print("\nLa placa pertenece a", type)
else:
print("\nPlaca no reconocida")
class Placa:
def TypePlaca(self):
placa=input("\nIngrese una placa: ")
if re.match("^([A-Z]|[0-9]){6}$", placa):
print("\nIngresaste una placa")
if re.match("^MA([A-Z]|[0-9]){4}$", placa):
type=("una motocicleta")
elif re.match("^MB([A-Z]|[0-9]){4}$", placa):
type=("un MetroBus")
elif re.match("^TA([A-Z]|[0-9]){4}$", placa):
type=("un taxi")
elif re.match("^E([A-Z]{1}|[0-9])+", placa):
type=("un vehiculo fiscal o judicial")
elif re.match("^CP([A-Z]|[0-9])+", placa):
type=("un vehiculo del canal")
elif re.match("^BU( |[0-9]{4})+$", placa):
type=("un Bus")
elif re.match("^HP( |[0-9]{4})+$", placa):
type=("un radioaficionado")
elif re.match("^A([A-Z]{1}|[0-9]{4})+$", placa):
type=("un auto regular")
elif re.match("^CC([A-Z]|[0-9])+$", placa):
type=("un cuerpo consular")
elif re.match("[0-9]+$", placa):
type=("una serie antigua")
elif re.match("^PR([A-Z]|[0-9])+", placa):
type=("un auto de prensa")
else:
type=("")
ShowPlaca(type)
else:
print ("Placa no valida")
placa=Placa()
if __name__=="__main__":
n=0
while n==0:
print(" \n Las placas siguen este formato:")
print("\n\nMoto: MA####\nAuto Regular: A(A-G)###")
print("Autos de prensa: PR####\nCuerpo Consular: CC####")
print("Radioaficionado: HP####\nBus: BU####")
print("Fiscal : E(A-Z)####\nTaxi: TA####\nMetroBus: MB####")
print("Las placas antiguas se conforman de 6 numeros.")
print("\n")
placa.TypePlaca()
print ("\nPresione 1 para hacer otra consulta o 2 para salir")
x = input ()
if x == '2':
n += 1
elif x == '1':
clear ()
exit ()
Please excuse the Spanish, this is how I have been trying to test it:
UPDATED
import unittest
from placas2 import TypePlaca
class Testplacas2(unittest.TestCase):
def test_TypePlaca(self):
placa = "123456"
self.assertEqual(placa.TypePlaca ,"una serie antigua...")
if __name__ == '__main__':
unittest.main()
When I try to run it gives me the following error:
Traceback (most recent call last):
File "C:\Users\movid\Documents\Programacion 3\Final\source\test_placas2.py", line 2, in <module>
from placas2 import TypePlaca
ImportError: cannot import name 'TypePlaca' from 'placas2' (C:\Users\movid\Documents\Programacion 3\Final\source\placas2.py)
To make things clear I have to test the 10 different types of car plates and see if that would give me the given result, while operating the program if my input is 123456, it does return "una serie antigua..." but most likely I need help structuring my test differently to get the result Im looking for.

Related

Why doesnt it print

I dont understand why it doesnt print the sentence. I have tried everything i can think off but im new to python is there something im missing?
def main():
print("1 = USD 2= GB pounds 3 = Japanse Yen")
valuta = input(" Welke valuta wilt u in wisselen voor de euro (graag het getal geven) ")
if __name__ == "__main__":
main()
Try changing your code to:
def main():
print("1 = USD 2= GB pounds 3 = Japanse Yen")
valuta = input(" Welke valuta wilt u in wisselen voor de euro (graag het getal geven) ")
print(valuta)
if __name__ == "__main__":
main()

applying a QUIT function to mini game in python

So I just started with python and I received the following task;
I need to create a mini game where the game choses a random number from 0-10.
Now I got most of my code but it seems I keep having issues with implementing a Quit option.
So the point is that the player can at any time give Quit as an answer and then the game quits.
It seems I can not attribute Quit in the right way.
When typing the Quit command (nee) I keep getting the following error message;
**Traceback (most recent call last):
File "C:\Users\aarabsa\PycharmProjects\projecten1\Lotto1.2.py", line 22, in <module>
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
ValueError: invalid literal for int() with base 10: 'nee'**
Could any of you guys give some advise ?
import random
import sys
print("Hello, wat is uw naam?")
naam = input()
print("Kan je de juiste cijfer raden tussen 0 en 10?")
answer = random.randint(0, 10)
guess = int(input('geef uw gekozen nummer: '))
TotalGuesses = 0
while guess != answer:
TotalGuesses += 1
if guess < answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
elif guess > answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
if guess == answer:
break
if guess == answer:
print('Correct ' + naam + '! Je hebt ' + str(TotalGuesses) + 'foutief geraden voordat je de juiste antwoord kon vinden!')
You should convert to an int only if you've first made sure the user didn't enter that string. For example:
guess = None # So it's defined
guess_string = input('geef uw gekozen nummer: ')
if guess_string.lower() == 'nee':
... # tell the user goodbye, or whatever
sys.exit()
else:
guess = int(guess_string)
Additionally, you could check that their input is a valid number before converting it and assigning it to guess. Here is an explanation of how you can do that.
Since you get user input multiple times in your program, you could wrap all that up in a function and just call that, so you don't have repeats in your code.

My variable that I created, is not working inside another function

I am dealing with a NameError at the moment. I have created multiple functions (for a project that I am working on). A variable that I've created, has to be used in multiple functions. I gave this variable as a parameter in all of the other functions and I had no problem at all. A friend of mine has written the menu function, which I have to connect with the functions I have created. I try to give "antwoorden_list" (which is created inside the function 'vragenLijst') as a parameter, because i need to use this variable inside the "menu" function.. Unfortunately I get this error message;
File "/Users/buni/Desktop/Leiden/IPOHBO/sorteerhoed/sorteerhoed menu.py", line 276, in <module>
main()
File "/Users/buni/Desktop/Leiden/IPOHBO/sorteerhoed/sorteerhoed menu.py", line 271, in main
menu(antwoorden_list)
NameError: name 'antwoorden_list' is not defined
I have no idea why this message is popping, because I have defined antwoorden_list as a parameter.
This is the part of my code which is not working;
##MAIN MENU
def menu(antwoorden_list):
color.write("\n" + "Welkom bij het ICT Sorteerhoed menu " ,"DEFINITION")
color.write(naam + "\n","KEYWORD")
infoApplicatie()
sleep(0.5)
print("_____________________________________\n")
print("1. Quiz beginnen")
print("2. Specialisaties bekijken")
print("3. Resultaten bekijken")
print("4. Programma sluiten")
print("_____________________________________\n")
sleep(0.9)
menuchoice = input("selecteer optie: ")
##SELECTION
if menuchoice == "1":
quiz(antwoorden_list)
elif menuchoice == "2":
specialisatiemenu()
elif menuchoice == "3":
resultatenmenu(antwoorden_list)
elif menuchoice == "4":
exit()
def vragenLijst(antwoorden_list):
print("De vragen worden geladen... ")
sleep(2.0)
print()
print("Goed om te weten: de vragen kunnen alleen beantwoord worden met 'ja' en 'nee', zolang je dit niet invoert, zullen de vragen verder gesteld worden.")
sleep(3.0)
print("---------------------------------------------------------------------------------------------------------------------------------------------------------")
vragen_list = open("vragenspecialisaties.txt").readlines()
vragen_list_index = list(enumerate(vragen_list, 1))
vragen_list_dict = dict(vragen_list_index)
antwoorden_list = []
while vragen_list_dict:
key = choice(list(vragen_list_dict))
antwoord = input(vragen_list_dict[key] + "(ja/nee): ")
if antwoord == "ja" or antwoord == "nee":
antwoorden_list.append((key, antwoord))
antwoorden_list.sort()
del vragen_list_dict[key]
return antwoorden_list
antwoorden_user = open("antwoorden_user.txt", "a")
antwoorden_user.write(naam + ": " + str(antwoorden_list) + "\n")
antwoorden_user.close()
def main():
menu(antwoorden_list)
infoApplicatie()
variabelen(antwoorden_list)
if __name__ == "__main__":
main()
I will appreciate all the help!
When you run your script, the main() function runs at first. So do the variable declarations inside main() before calling the functions.

Python file executable error

I did a fuel calculator program for a game with python and then I compiled to .exe with cx_Freeze. It converts it well to .exe and I can open the executable but when the script interacts with the user the window closes after pressing enter when the user introduce the requested information.
This is one part of the code, after requesting some information to the user the program does some calculations but I think it's irrelevant because the problem is in the input. I want that the program doesn't close when the user press enter in the input of info requested.
import sys
COMBUSTIBLE=chr(raw_input("Introduce unidad de combustible: "))
DURACION=chr(raw_input("Introduce unidad de duracion: "))
if COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos" and DURACION != "vueltas" and DURACION != "tiempo" and DURACION != "km":
print "Error: Ambos argumentos son invalidos"
print "Primer argumento debe ser 'litros' o 'kilos'"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(1)
elif COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos":
print "Error: Primer argumento invalido"
print "Primer argumento debe ser 'litros' o 'kilos'"
sys.exit(2)
elif DURACION != "tiempo" and DURACION != "vueltas" and DURACION != "km":
print "Error: Segundo argumento invalido"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(3)
else:
pass
# TIPO 1 - LITROS - VUELTAS
if COMBUSTIBLE == "l" and DURACION == "v":
# DATA REQUEST
RACE_DURATION=int(raw_input("Introduce el total de vueltas de la carrera: "))
CAR_FUEL=float(raw_input("Introduce los litros totales del coche: "))
FUEL_PER_LAP=float(raw_input("Introduce el consumo medio en litros por vuelta: "))
The window will be closed right after your proggram finished executing. So if you want the window stays open you should remove sys.exit() statements and add something at the end of your script like:
input("Press any key to exit: ")
in Python 3 or
raw_input("Press any key to exit: ")
in Python 2

NameError: global name 'Circulo_Mohr_v1_2' is not defined

I'm trying make a simple menu (options: 1,2,3) and the second option (input 2) should run a graphical menu.
When I try run python reports a NameError ("global name 'Circulo_Mohr_v1_2' is not defined").
I don't know the correct syntax
print "inicio"
import sys
from librerias import Circ_Mohr_motor_v2
import librerias.Circulo_Mohr_v1_2
from librerias import prueba_importacion
'''
def definicion_ventana():
Circulo_Mohr_v3_0.Ui_CalculodecirculosMohr()
#Ui_CalculodecirculosMohr.setupUi()
'''
def seleccion_de_libreria():
print '''Escoger opcion:
1) motor
2) Ventana
3) test
'''
opcion = raw_input ("Opcion seleccionada: ")
opcion = int (opcion)
if opcion == 1:
print "se ejecuta el motor de calculo"
punto_Ax = raw_input ("Insertar coordenada X de primer punto: ")
punto_Ay = raw_input ("Insertar coordenada Y de primer punto: ")
punto_Bx = raw_input ("Insertar coordenada X de segundo punto: ")
punto_By = raw_input ("Insertar coordenada Y de segundo punto: ")
Circ_Mohr_motor_v2.circulo_mohr(punto_Ax,punto_Ay,punto_Bx,punto_By)
elif opcion == 2:
print "se ejecuta la funcion ventana"
Circulo_Mohr_v1_2.Ui_CalculodecirculosMohr()
print "fin la funcion ventana"
else:
print "se ejecuta el test"
prueba_importacion.prueba_01()
seleccion_de_libreria()
print "fin"
How can I fix that?
try replace
import librerias.Circulo_Mohr_v1_2
with
from librerias.Circulo_Mohr_v1_2 import Ui_CalculodecirculosMohwith
and call directly Ui_CalculodecirculosMohr()
Ui_CalculodecirculosMohr()

Categories