⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sect03.htm

📁 this is the most basic to learn python
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!--
This document was converted from RTF source: 
By rtftohtml 4.19
See http://www.sunpack.com/RTF
Filename:TIPython.rtf
Application Directory:c:\tools\rtf2html\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:12/31/2001
Translation Time:08:24:12
Translation Platform:Win32
Number of Output files:18
This File:Sect03.htm
SplitDepth=1
SkipNavPanel=1
SkipLeadingToc=1
SkipTrailingToc=1
GenContents=1
GenFrames=1
GenIndex=1
-->
<HEAD lang="en"><META http-equiv="Content-Type" content="text/html">
<TITLE>2: Unit Testing</TITLE>

<script language="JavaScript">
</script>
</head>


<BODY  BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
  <a href="http://www.MindView.net">
  <img src="mindview.gif" alt="MindView Inc." BORDER = "0"></a>
  <CENTER>
    <FONT FACE="Verdana, Tahoma, Arial, Helvetica, Sans" size = "-1">
    <!-- [ <a href="README.txt">Viewing Hints</a> ]
    [ <a href="RevisionHistory.htm">Revision History</a> ] -->
    [ <a href="http://www.mindview.net/Books/TIPython/">Book Home Page</a> ]
    [ <a href="http://www.mindview.net/Etc/MailingList.html">Free Newsletter</a> ] <br>
    [ <a href="http://www.mindview.net/Seminars">Seminars</a> ]
    [ <a href="http://www.mindview.net/CDs">Seminars on CD ROM</a> ]
    [ <a href="http://www.mindview.net/Services">Consulting</a> ]
    </FONT>
  <H2><FONT FACE="Verdana, Tahoma, Arial, Helvetica, Sans">
  Thinking in Python<br>
  <small>Revision 0.1.2 (12/31/01) -- Incomplete and Unfinished</small></FONT></H2>
  <H3><FONT FACE="Verdana, Tahoma, Arial, Helvetica, Sans">
  by Bruce Eckel &copy;2002 MindView, Inc.</FONT></H3>
  
    <FONT FACE="Verdana, Tahoma, Arial, Helvetica, Sans" size = "-1">
     [ <a href="Sect02.htm">Previous Chapter</a> ] 
    
    [ <a href="javascript:window.location.href = 'Index.htm';">Table of Contents</a> ] 
  
        [ <a href="DocIdx.htm">Index</a> ]
        
     [ <a href="Sect04.htm">Next Chapter</a> ] 
    </FONT>
    
  </CENTER>
  </P></DIV><A NAME="_Toc534420071"></A><A NAME="Heading22"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H1 ALIGN="LEFT">
2: Unit Testing</H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia" SIZE=4 COLOR="Red">This chapter has not
had any significant translation yet.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia" SIZE=4>One of the important recent
realizations is the dramatic value of unit testing.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_77">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This is the process of building
integrated tests into all the code that you create, and running those tests
every time you do a build. It&#146;s as if you are extending the compiler,
telling it more about what your program is supposed to do. That way, the build
process can check for more than just syntax errors, since you teach it how to
check for semantic errors as well.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_78">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">C-style programming languages, and C++ in
particular, have typically valued performance over programming safety. The
reason that developing programs in Java is so much faster than in C++ (roughly
twice as fast, by most accounts) is because of Java&#146;s safety net: features
like better type checking, enforced exceptions and garbage collection. By
integrating unit testing into your build process, you are extending this safety
net, and the result is that you can develop faster. You can also be bolder in
the changes that you make, and more easily refactor your code when you discover
design or implementation flaws, and in general produce a better product, faster.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_79">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Unit testing is not generally considered
a design pattern; in fact, it might be considered a &#147;development
pattern,&#148; but perhaps there are enough &#147;pattern&#148; phrases in
the world already. Its effect on development is so significant that it will be
used throughout this book, and thus will be introduced here.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_80">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">My own experience with unit testing began
when I realized that every program in a book must be automatically extracted and
organized into a source tree, along with appropriate makefiles (or some
equivalent technology) so that you could just type <B>make</B> to build the
whole tree. The effect of this process on the code quality of the book was so
immediate and dramatic that it soon became (in my mind) a requisite for any
programming book&#151;how can you trust code that you didn&#146;t compile? I
also discovered that if I wanted to make sweeping changes, I could do so using
search-and-replace throughout the book, and also bashing the code around at
will. I knew that if I introduced a flaw, the code extractor and the makefiles
would flush it out.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_81">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As programs became more complex, however,
I also found that there was a serious hole in my system. Being able to
successfully compile programs is clearly an important first step, and for a
published book it seemed a fairly revolutionary one&#151;usually due to the
pressures of publishing, it&#146;s quite typical to randomly open a programming
book and discover a coding flaw. However, I kept getting messages from readers
reporting semantic problems in my code (in <I>Thinking in Java</I>). These
problems could only be discovered by running the code. Naturally, I understood
this and had taken some early faltering steps towards implementing a system that
would perform automatic execution tests, but I had succumbed to the pressures of
publishing, all the while knowing that there was definitely something wrong with
my process and that it would come back to bite me in the form of embarrassing
bug reports (in the open source world, embarrassment is one of the prime
motivating factors towards increasing the quality of one&#146;s code!).
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_82">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The other problem was that I was lacking
a structure for the testing system. Eventually, I started hearing about unit
testing and
JUnit</FONT><A NAME="fnB11" HREF="#fn11">[11]</A><FONT FACE="Georgia">, which
provided a basis for a testing structure. However, even though JUnit is intended
to make the creation of test code easy, I wanted to see if I could make it even
easier, applying the Extreme Programming principle of &#147;do the simplest
thing that could possibly work&#148; as a starting point, and then evolving the
system as usage demands (In addition, I wanted to try to reduce the amount of
test code, in an attempt to fit more functionality in less code for screen
presentations). This chapter is the result.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_83">Add Comment</A></FONT><A NAME="_Toc534420072"></A><BR></P></DIV>
<A NAME="Heading23"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H2 ALIGN="LEFT">
Write tests first</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As I mentioned, one of the problems that
I encountered&#151;that most people encounter, it turns out&#151;was
submitting to the pressures of publishing and as a result letting tests fall by
the wayside. This is easy to do if you forge ahead and write your program code
because there&#146;s a little voice that tells you that, after all,
you&#146;ve got it working now, and wouldn&#146;t it be more
interesting/useful/expedient to just go on and write that other part (we can
always go back and write the tests later). As a result, the tests take on less
importance, as they often do in a development project.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_84">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The answer to this problem, which I first
found described in <I>Extreme Programming Explained</I>, is to write the tests
<I>before</I> you write the code. This may seem to artificially force testing to
the forefront of the development process, but what it actually does is to give
testing enough additional value to make it essential. If you write the tests
first, you:
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_85">Add Comment</A></FONT><BR></P></DIV>
<OL>
<LI><FONT FACE="Verdana">	</FONT><FONT FACE="Georgia">Describe what the code is
supposed to do, not with some external graphical tool but with code that
actually lays the specification down in concrete, verifiable terms.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_86">Add Comment</A></FONT><LI><FONT FACE="Verdana">	</FONT><FONT FACE="Georgia">Provide
an example of how the code should be used; again, this is a working, tested
example, normally showing all the important method calls, rather than just an
academic description of a library.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_87">Add Comment</A></FONT><LI><FONT FACE="Verdana">	</FONT><FONT FACE="Georgia">Provide
a way to verify when the code is finished (when all the tests run correctly).
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_88">Add Comment</A></FONT></OL><DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Thus,
if you write the tests first then testing becomes a development tool, not just a
verification step that can be skipped if you happen to feel comfortable about
the code that you just wrote (a comfort, I have found, that is usually wrong).
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_89">Add Comment</A></FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">You can find convincing arguments in
<I>Extreme Programming Explained</I>, as &#147;write tests first&#148; is a
fundamental principle of XP. If you aren&#146;t convinced you need to adopt any
of the changes suggested by XP, note that according to Software Engineering
Institute (SEI) studies, nearly 70% of software organizations are stuck in the
first two levels of SEI's scale of sophistication: chaos, and slightly better
than chaos. If you change nothing else, add automated testing.
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_90">Add Comment</A></FONT><A NAME="_Toc534420073"></A><BR></P></DIV>
<A NAME="Heading24"></A><FONT FACE = "Verdana, Tahoma, Arial, Helvetica, Sans"><H2 ALIGN="LEFT">
Simple Python testing</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Sanity check for a quick test of the
programs in this book, and to append the output of each program (as a string) to
its listing:
<A HREF="http://www.mindview.net/Books/TIPython/BackTalk/FindPage/A_91">Add Comment</A></FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE>#: SanityCheck.py
<font color=#0000ff>import</font> string, glob, os
# Do <font color=#0000ff>not</font> include the following <font color=#0000ff>in</font> the automatic
# tests:
exclude = (<font color=#004488>"SanityCheck.py"</font>, <font color=#004488>"BoxObserver.py"</font>,)

<font color=#0000ff>def</font> visitor(arg, dirname, names):
  dir = os.getcwd()
  os.chdir(dirname)
  <font color=#0000ff>try</font>:
    pyprogs = [p <font color=#0000ff>for</font> p <font color=#0000ff>in</font> glob.glob('*.py') 
               <font color=#0000ff>if</font> p <font color=#0000ff>not</font> <font color=#0000ff>in</font> exclude ]
    <font color=#0000ff>if</font> <font color=#0000ff>not</font> pyprogs: <font color=#0000ff>return</font>
    <font color=#0000ff>print</font> '[' + os.getcwd() + ']'
    <font color=#0000ff>for</font> program <font color=#0000ff>in</font> pyprogs:
      <font color=#0000ff>print</font> '\t', program
      os.system(<font color=#004488>"python %s &gt; tmp"</font> % program)
      file = open(program).read()
      output = open('tmp').read()
      # Append output <font color=#0000ff>if</font> it's <font color=#0000ff>not</font> already there:
      <font color=#0000ff>if</font> file.find(<font color=#004488>"output = '''"</font>) == -1 <font color=#0000ff>and</font> \
        len(output) &gt; 0:
        divider = '#' * 50 + '\n'
        file = file.replace('#' + ':~', '#&lt;hr&gt;\n')
        file += <font color=#004488>"output = '''\n"</font> + \
          open('tmp').read() + <font color=#004488>"'''\n"</font>
        open(program,'w').write(file)
  <font color=#0000ff>finally</font>:
    os.chdir(dir)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -