Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |
 User Name: Password: Remember me

New Free Tools on Dev Shed!
We're Excited to announce that Dev Shed now has 70 free tools on the site. To learn more, click here!

 Dev Shed Forums Sponsor:
#1
July 21st, 2013, 08:18 AM
 leonnaley2
Contributing User

Join Date: Jan 2013
Posts: 67
Time spent in forums: 23 h 24 m 55 sec
Reputation Power: 1
Unittesting, tkinter howto?

Hey, I've recently started to learn myself tkinter, and made a simple calculator program.
I know the basics of unitttesting, but I can't really get my head around how I could end up with my current program using unittests as the "driving force". And what I should unit test in a simple program such as this. Does anyone have any hints/tips to how I should do that? or improvements to my current program?

Code:
```#!/usr/bin/env python2
# coding=utf-8
#This module is made to work in python2

#GENERAL INFORMATION
__author__ = "Leon Naley"
__copyright__ = "Copyright (c) 2013 Leon Naley"
__version_info__ = ["Alpha Version", "0", "1"]
__version__ = '.'.join(__version_info__[1:])

#IMPORTS AND SETS UP MODULES
import sys
import Tkinter as tk

#DEFINES FUNCTIONS
def fCalculate(sOperator):
dsOperator.set(sOperator)
try:
fVar1 = float(dsTextField1.get())
fVar2 = float(dsTextField2.get())
except ValueError:
dsResult.set("invalid input")
return

if sOperator == "+":
fAnswer = fVar1 + fVar2
if sOperator == "-":
fAnswer = fVar1 - fVar2
if sOperator == "*":
fAnswer = fVar1 * fVar2
if sOperator == "/":
if fVar2 == 0:
dsResult.set("You can't divide by zero")
return
fAnswer = fVar1 / fVar2

else:

#RUNS THE MAIN PROGRAM
if __name__ == "__main__":
#Creates a window
owMain = tk.Tk()
owMain.geometry("450x450+200+200")
owMain.title("Calculator")

#Creates some tkinter dynamic variables
dsTextField1 = tk.StringVar()
dsTextField2 = tk.StringVar()
dsOperator = tk.StringVar()
dsResult = tk.StringVar()

#Creates widgets
weTextField1 = tk.Entry(owMain, textvariable=dsTextField1, justify="right")

wlOperator = tk.Label(textvariable=dsOperator)
weTextField2 = tk.Entry(owMain, textvariable=dsTextField2, justify="right")

wlResult = tk.Label(textvariable=dsResult)

wbPlus = tk.Button(owMain, text="+", command=lambda: fCalculate("+"))
wbMinus = tk.Button(owMain, text="-", command=lambda: fCalculate("-"))
wbMultiplicate = tk.Button(owMain, text="*", command=lambda: fCalculate("*"))
wbDivide = tk.Button(owMain, text="/", command=lambda: fCalculate("/"))

#Packs the widgets in a grid
tk.Label(text=" ").grid(row=0, column=0)
weTextField1.grid(row=0, column=1, columnspan=3)

wlOperator.grid(row=1, column=0)
weTextField2.grid(row=1, column=1, columnspan=3)

tk.Label(text="=").grid(row=2, column=0)
wlResult.grid(row=2, column=1, columnspan=3)

wbPlus.grid(row=4, column=0)
wbMinus.grid(row=4, column=1)
wbMultiplicate.grid(row=4, column=2)
wbDivide.grid(row=4, column=3)
#Runs the main Tkinter loop
owMain.mainloop()```

#2
July 21st, 2013, 03:49 PM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,186
Time spent in forums: 1 Month 3 Weeks 2 Days 12 h 59 m 52 sec
Reputation Power: 455
Novel calculator, the inputs remain. You can easily try various operations with them.

I wouldn't convert the answer to int unless the inputs are also int, in which case I'd convert with int not float. Try your program to add 1e30 to 0 . OK, I actually liked the feature as implemented and struggled a bit to find why it's wrong. It is wrong.

You want to use unittest . unit testing demands discipline. You'll want to run all the unit tests in a directory or project. You'll eventually need to write a frame work that searches for test files, causing you to enforce a file naming policy, such as
module.py and module_test.py
nosetests (search the internet for them) might have already done that work for you.

You also want to automate gui testing. I haven't done it but I suppose you'd need to send artificial signals which are also bound within your program.
widget.bind('<<artificial-event>>', callable)
Or maybe you could use one of those programs that simulates mouse clicks. Or maybe your window system maintains an event log you can edit and play back in some controlled manner that gives you time to verify program outputs.

I would write your calculator program without passing so much data via global variables. Give a hoot, don't pollute. Keep your name spaces clean. Parts of your program will become reusable. I use lambda to shorten programs. I don't use them namelessly. I name them.
Code:
```#!/usr/bin/env python2
# coding=utf-8

import sys
if sys.version[0] != '2':
sys.stderr.write('This module is made to work in python2\n')
sys.exit(1)

import operator
import Tkinter as tk

class compute:

operations = {symbol: getattr(operator, attribute) for (symbol, attribute,) in zip('+-*/','add sub mul div'.split())}

def __init__(self, dsOperator,dsTextField1,dsTextField2,dsResult):
self. dsOperator = dsOperator
self.dsTextField1 = dsTextField1
self.dsTextField2 = dsTextField2
self.dsResult = dsResult

add = lambda self: self('+')
sub = lambda self: self('-')
mul = lambda self: self('*')
div = lambda self: self('/')

def __call__(self, sOperator):
self.dsOperator.set(sOperator)
try:
fVar1 = float(self.dsTextField1.get())
fVar2 = float(self.dsTextField2.get())
except ValueError:
result = "invalid input"
else:
try:
fAnswer = self.__class__.operations[sOperator](fVar1, fVar2)
except:
result = "Trouble!  Did you divide by zero?"
else:
else:
self.dsResult.set(str(result))

#RUNS THE MAIN PROGRAM
if __name__ == "__main__":
#Creates a window
owMain = tk.Tk()
owMain.geometry("450x450+200+200")
owMain.title("Calculator")

#Creates some tkinter dynamic variables
dsTextField1 = tk.StringVar()
dsTextField2 = tk.StringVar()
dsOperator = tk.StringVar()
dsResult = tk.StringVar()

#Creates widgets
weTextField1 = tk.Entry(owMain, textvariable=dsTextField1, justify="right")

wlOperator = tk.Label(textvariable=dsOperator)
weTextField2 = tk.Entry(owMain, textvariable=dsTextField2, justify="right")

wlResult = tk.Label(textvariable=dsResult)

actions = compute(dsOperator,dsTextField1,dsTextField2,dsResult)

wbPlus = tk.Button(owMain, text="+", command = actions.add)
wbMinus = tk.Button(owMain, text="-", command = actions.sub)
wbMultiplicate = tk.Button(owMain, text="*", command = actions.mul)
wbDivide = tk.Button(owMain, text="/", command = actions.div)

#Packs the widgets in a grid
tk.Label(text=" ").grid(row=0, column=0)
weTextField1.grid(row=0, column=1, columnspan=3)

wlOperator.grid(row=1, column=0)
weTextField2.grid(row=1, column=1, columnspan=3)

tk.Label(text="=").grid(row=2, column=0)
wlResult.grid(row=2, column=1, columnspan=3)

wbPlus.grid(row=4, column=0)
wbMinus.grid(row=4, column=1)
wbMultiplicate.grid(row=4, column=2)
wbDivide.grid(row=4, column=3)
#Runs the main Tkinter loop
owMain.mainloop()```
My version is around 10 lines longer than yours, but primarily the purpose of rewrite was to demonstrate how to localize data to make a reuseable class.
__________________
[code]Code tags[/code] are essential for python code!

#3
July 22nd, 2013, 08:43 AM
 leonnaley2
Contributing User

Join Date: Jan 2013
Posts: 67
Time spent in forums: 23 h 24 m 55 sec
Reputation Power: 1
Thanks for great input I've modified my code and made it cleaner in general and abit easier to unittest aswell.
Is this better?
Code:
```#!/usr/bin/env python2
#coding=utf-8
#this module is made to work in python2

#GENERAL INFORMATION
__author__ = "Leon Naley"
__copyright__ = "Copyright (c) 2013 Leon Naley"
__version_info__ = ["Alpha Version", "0", "2"]
__version__ = '.'.join(__version_info__[1:])

#IMPORTS AND SETS UP MODULES
import sys
import Tkinter as tk

#CHECKS PYTHON VERSION
if sys.version[0] != '2':
sys.stderr.write('This module is made to work in python2\n')
sys.exit(1)

#DEFINES FUNCTIONS
def fsCalculate(sOperator, sFirstNumber, sSecondNumber):
#Converts the two numbers into int or float,
#   depending on what they should be
lNumbers = []
for sNumber in [sFirstNumber, sSecondNumber]:
if "." in sNumber:
lNumbers.append(float(sNumber))
else:
lNumbers.append(int(sNumber))

#Does the calculation and checks for zero division errors
if sOperator == "+":
xAnswer = lNumbers[0] + lNumbers[1]
if sOperator == "-":
xAnswer = lNumbers[0] - lNumbers[1]
if sOperator == "*":
xAnswer = lNumbers[0] * lNumbers[1]
if sOperator == "/":
try:
xAnswer = float(lNumbers[0]) / float(lNumbers[1])
except ZeroDivisionError:
return("You can't divide by zero.")

#Transform the answer into an int,
#   if it doesn't need any decimals to be accurate

#Return the answer back as

#DEFINES CLASSES
class cCalculator():
def __init__(self):
#Creates a window
self.owMain = tk.Tk()
self.owMain.title("Calculator")
#Sets the geometry of the window
self.iWidth = 220
self.iHeight = 110
self.iLeft = (self.owMain.winfo_screenwidth() / 2) - (self.iWidth / 2)
self.iTop = (self.owMain.winfo_screenheight() / 2) - (self.iHeight / 2)
self.owMain.geometry(str(self.iWidth) + "x" +
str(self.iHeight) + "+" +
str(self.iLeft) + "+" +
str(self.iTop))

#Creates tkinter dynamic variables
self.dsUpperEntry = tk.StringVar()
self.dsLowerEntry = tk.StringVar()
self.dsOperator = tk.StringVar()
self.dsResultEntry = tk.StringVar()

#Creates lambda functions for use with buttons
fAdd = lambda: self.mDisplayResult("+")
fSubtract = lambda: self.mDisplayResult("-")
fMultiplicate = lambda: self.mDisplayResult("*")
fDivide = lambda: self.mDisplayResult("/")

#Creates widgets for row0
self.weUpper = tk.Entry(self.owMain, textvariable=self.dsUpperEntry,
justify="right")
#Creates widgets for row1
self.wlOperator = tk.Label(self.owMain, textvariable=self.dsOperator)
self.weLower = tk.Entry(self.owMain, textvariable=self.dsLowerEntry,
justify="right")
#Creates widgets for row2
self.weResult = tk.Entry(self.owMain, textvariable=self.dsResultEntry,
justify="right")
#Creates widgets for row3
self.wbSub = tk.Button(self.owMain, text="-", command=fSubtract)
self.wbMul = tk.Button(self.owMain, text="*", command=fMultiplicate)
self.wbDiv = tk.Button(self.owMain, text="/", command=fDivide)

#Packs the widgets into row0
tk.Label(text=" ").grid(row=0, column=0)
self.weUpper.grid(row=0, column=1, columnspan=3)
#Packs the widgets into row1
self.wlOperator.grid(row=1, column=0)
self.weLower.grid(row=1, column=1, columnspan=3)
#Packs the widgets into row2
tk.Label(text="=").grid(row=2, column=0)
self.weResult.grid(row=2, column=1, columnspan=3)
#Packs the widgets into row3
self.wbSub.grid(row=3, column=1)
self.wbMul.grid(row=3, column=2)
self.wbDiv.grid(row=3, column=3)

def mDisplayResult(self, sOperator):
'''This function will complete the math operation,
and update the result entry and the operator label text.'''
#Calculate result
sResult = fsCalculate(sOperator, self.dsUpperEntry.get(),
self.dsLowerEntry.get())

#Change entry field, and operator label text
self.dsResultEntry.set(sResult)
self.dsOperator.set(sOperator)

#RUNS THE MAIN PROGRAM
if __name__ == "__main__":
#Creates an object for the calculator window
oCalculator = cCalculator()

#Runs the main Tkinter loop
oCalculator.owMain.mainloop()```

Last edited by leonnaley2 : July 22nd, 2013 at 09:00 AM.

#4
July 22nd, 2013, 10:34 AM
 newjentic
Registered User

Join Date: Jul 2013
Posts: 1
Time spent in forums: 11 m 52 sec
Reputation Power: 0

thanks

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Unittesting, tkinter howto?

## Developer Shed Advertisers and Affiliates

 Thread Tools Search this Thread Search this Thread: Advanced Search Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts vB code is On Smilies are On [IMG] code is On HTML code is Off
 View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox Forum Jump Please select one User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home -------------------- Programming Languages    PHP Development        PHP FAQs and Stickies    Perl Programming        Perl FAQs and Stickies    C Programming        C Programming FAQs and Stickies    Java Help        Java FAQs    Python Programming        Python Programming FAQs    Ruby Programming        Ruby Programming FAQs    Game Development        Game Development FAQs Programming Languages - More    ASP Programming        ASP Programming FAQs    .Net Development        .Net Development FAQs    Visual Basic Programming        Visual Basic Programming FAQs    Software Design        Software Design FAQs    ColdFusion Development        ColdFusion Development FAQs    Delphi Programming        Delphi Programming FAQs    Regex Programming        Regex Programming FAQs    XML Programming        XML Programming FAQs    Other Programming Languages        Other Programming Languages FAQs Web Design    HTML Programming        HTML Programming FAQs    JavaScript Development        JavaScript Development FAQs    CSS Help        CSS Help FAQs    Flash Help        Flash Help FAQs    Photoshop Help        Photoshop Help FAQs    Web Design Help        Web Design Help FAQs    Website Critiques        Website Critiques FAQs    Search Engine Optimization        Search Engine Optimization FAQs Mobile Programming    Mobile Programming        Mobile Programming FAQs    iPhone SDK Development        iPhone SDK Development FAQs    Android Development        Android Development FAQs    BlackBerry Development        BlackBerry Development FAQs Web Site Management    Business Help        Business Help FAQs    Development Software        Development Software FAQs    Scripts        Scripts FAQs Databases    Database Management        Database Management FAQs    DB2 Development        DB2 Development FAQs    MySQL Help        MySQL Help FAQs    PostgreSQL Help        PostgreSQL Help FAQs    Firebird SQL Development        Firebird SQL Development FAQs    MS SQL Development        MS SQL Development FAQs    Oracle Development        Oracle Development FAQs    LDAP Programming        LDAP Programming FAQs System Administration    Mail Server Help        Mail Server Help FAQs    Apache Development        Apache Development FAQs    Security and Cryptography        Security and Cryptography FAQs    Antivirus Protection        Antivirus Protection FAQs    DNS        DNS FAQs    IIS        IIS FAQs    Networking Help        Networking Help FAQs    FTP Help        FTP Help FAQs Operating Systems    BSD Help        BSD Help FAQs    Linux Help        Linux Help FAQs    UNIX Help        UNIX Help FAQs    Windows Help        Windows Help FAQs    Mac Help        Mac Help FAQs Web Hosting    Web Hosting        Web Hosting FAQs    Free Web Hosting        Free Web Hosting FAQs    Web Hosting Requests        Web Hosting Requests FAQs    Web Hosting Offers        Web Hosting Offers FAQs Computer Hardware    Computer Hardware    CPUs        CPUs FAQs    Cooling        Cooling FAQs    Embedded Programming        Embedded Programming FAQs    Motherboards        Motherboards FAQs    Multimedia Hardware        Multimedia Hardware FAQs Other    Dev Shed Lounge        Dev Shed Lounge FAQs    Development Articles        Development Articles FAQs    Beginner Programming        Beginner Programming FAQs    Hire A Programmer        Hire A Programmer FAQs    Project Help Wanted        Project Help Wanted FAQs Latest News Updated Hourly    Technology News    Business News    Science News Forum Information    Forum Rules/Guidelines        Forum Rules/Guidelines FAQs    Forum Announcements        Forum Announcements FAQs    Dev Shed Gaming Center        Go to the Dev Shed Battle Arena        Go to the Dev Shed Arcade Games        Go to the Legend of the Green Dragon    Suggestions & Feedback        Suggestions & Feedback FAQs

 Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |