[Tutor] Best Code testing practice?

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Jun 21 20:07:47 CEST 2013


Matt D wrote:
> Sent: Thursday, June 20, 2013 6:44 AM
> To: tutor at python.org
> Subject: [Tutor] Best Code testing practice?
> 
> Hey guys!
> Is there a fast way test some piece of code?  I would like to be able to
> look at the GUI I am making with out changing the file in dir 'baz' and
> running the actual program (which is quite extensive).  Like if I could
> just have a .py file with only the smallest amount of code possible to
> make the GUI run, and I could run the .py file from the interpreter to
> make the GUI run, this would be beautiful.  This allow me to
> easily/quickly experiment with code and test my code.  Do we need an IDE
> for this sort of thing or can we just use the interpreter?  OMG i was up
> till 3am trying to find some way to do this.
> Thanks!
> --
> Matt D
> ------------

Have you heard of the MVC model? The idea is that you separate the 
business logic from the "view" or UI. The "controller" contains
all the business logic (or work actually being done).

Note the below is half pseudo-code just to give you an example.
I have neither tested the code nor expect it to actually run.

=========================================
# File myapp/ui.py
class UI(wx.Frame):
    def __init__( self, controller, *args, **kwargs ):
        self.controller = controller
        super(wx.Frame, self).__init__(*args, **kwargs)
    def updateData(self):
        data = self.controller.get_data()
        self.display_data(data)

# File myapp/test.py
class TestController(object):
    def __init__( self, *args, *kwargs ): #accept same options of real controller
        pass # Don't need real data
    def get_date(self):
        ''' return hard coded test data or generate test data'''
        return [ 1,2,34,4,5 ] 

if __name__ == "__main__":
    app = wx.App() # or whatever the setup for wx should be.
    from myapp.ui import UI
    UI(TestController())
    
# file myapp/main.py
from myapp.ui import UI
from myapp.controller import Controller

if __name__ == "__main__":
    # setup wx
    f = UI(Controller())
    f.Fit() # or Show() or whatever

=========================================

python myapp/test.py
python myapp/main.py


Now you can test your changes to business logic and your user
interface separately. You can even look into automated testing.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list