Pydev coverage test Python coverage and other usage

Source: Internet
Author: User
Tags ibm developerworks

1. Help ---> Software Updates ---> Find and install ....

2. Select search for new features for install and click Next. In the displayed window, select new remote site. In this case, a dialog box is displayed, asking you to enter the new site name and link. Here, enter pydev as the name item. Of course, you can enter another name. Enter http://www.fabioz.com/pydev/updatesin the link, or enter http://pydev.sourceforge.net/updates. Then, click OK.

In this way, a new pydev site is created, select the site, and finish. Next, Eclipse's update manager will search for the installation package in the input site, select the search result pydev, and click Next.

3.

  1. Read the license terms. If accepted, click Next. Go to the installation path selection page, use the default settings, and finish.
  1. Eclipse update manager downloads pydev. You can view the download progress in the eclipse taskbar. After the download is complete, a page is displayed that requires you to confirm whether the installation is complete. Click Install all to start the installation.

After installation, restart eclipse to make the installation take effect.

Verify if pydev is successfully installed

How can I verify that eclipse update manager has successfully installed the required pydev plug-in?

Select help-> about eclipse SDK-> plug-in details to display the about eclipse SDK plug-ins window, which lists all installed Eclipse plug-ins. Check whether there are at least five in the plug-in ID column, using COM. Python. pydev andOrg. Python. pydev. If yes, pydev has been successfully installed. Otherwise, some problems may occur during installation. You need to analyze the problems according to the specific problems.

Figure 3. Verify the pydev plug-in

Configure pydev

After installing pydev, You need to configure the python/Jython interpreter. The configuration process is simple.

On the eclipse menu bar, choose Window> preferences> pydev> interpreter-(Python/Jython). Configure the python/Jython interpreter here. The following describes how to configure python.

First, you must add an installed interpreter. Here, python is installed in the C: \ python25 path. Click new and select Python interpreter python.exe. A window containing multiple check boxes is displayed.Pythonpath And click OK.

Figure 4. Configure pydev

Next, check whether the configuration result is correct.

In SystemPythonpath To check whether the paths added during the configuration process are included. All library folders required by the system are listed here.

In addition, the built-in Python libraries are listed in forced builtin libs. For python, there are about 50 built-in libraries and about 30 built-in libraries for Jython.

In this way, the python interpreter is configured.




Back to Top

Pydev package Explorer

Create a project

Before proceeding, you need to create a new project. On the eclipse menu bar, choose File> New> Project> pydev project and click Next.

Figure 5. Create a pydev Project

The pydev project window is displayed. Enter the project name, select the working path, select the version type of the python interpreter, select the check box, and click Next to enter the associated project window, if you do not need to associate other projects, click Finish to create the project.

Create Python packages and modules

Next, create a python package and module in the project you just created.

  1. Go to the pydev perspective. In Python package explorer, right-click SRC, choose new> pydev package, enter the package name, and click Finish. The Python package is created, automatically generate _ init __. py file, which does not contain any content.

Note: If the "create default SRC folder and add it to the pythonpath" check box is not selected during project creation, you must use File> New> Other> source folder to manually create a source code folder.

  1. After creating the pydev package, right-click the created package, select new-> pydev module, enter the module name, and click Finish. In this way, the python module is built.

Edit source program

I will not introduce some basic editing methods of the source program. The following describes some useful editing functions provided by pydev.

  1. Syntax Error prompt

When creating and modifying a program, Python developers can promptly discover syntax errors during the editing process, which is undoubtedly important to the quality and progress of the entire project development. In the python perspective, the source code of the Project is listed in the pydev package explorer. Double-click a python file. If the file contains a syntax error, the error is displayed in a conspicuous way.

Figure 6. pydev File Syntax Error prompt

If you want to display all files with syntax errors in the entire project, you can switch from the python perspective to the Java perspective. In the Java package, a small Red Cross marks all Python files with syntax errors.

Figure 7. pydev project syntax error prompt

  1. Source code editing Assistant)

The source code editing Assistant (CA), as its name implies, is used to help developers edit source programs. It provides many convenient and practical functions to guide developers in efficient and fast project development.

You can activate CA by pressing CTRL + 1. It supports the following functions:

Pydev

  1. Move import to global scope
  2. Create docstring
  3. Assign result to new local variable (or field)
  4. Assign parameters to attributes
  5. Surround code with try... try t or try... finally

Pydev extensions

  1. Make import for undefined token
  2. Ignore Error
  3. Don't analyze Module

When installing pydev, The pydev and pydev extensions packages are installed, so these functions of CA are now supported. First, we will introduce how to use the CA function included in pydev.

  • CA functions of pydev
  1. Move import to global scope

Take the following code as an example. move the cursor to import sys and press Ctrl + 1 to activate CA. "Move import to global scope" appears in the label. Press enter to apply this function. If you do not want to apply this function, Press ESC to cancel it.

#!/usr/bin/python –usys.path.append(“./VirtualFS”)import sys

After this function is applied, import sys is successfully moved to the global range, eliminating the previous errors. The changed code is as follows.

#!/usr/bin/python –uimport syssys.path.append(“./VirtualFS”)
  1. Create docstring

The create docstring function automatically adds parameter annotations to the function. Move the cursor to the following code line, and press Ctrl + 1 to activate CA. "Make docstring" appears in the tab bar ".

def __init__(self, dbUser, dbPswd, dbHost):

After you press enter to apply this function, a parameter annotation is automatically added to the function.

def __init__(self, dbUser, dbPswd, dbHost):  '''    @param virtualOperator:  @param database:  @param hostname:  @param workDir: '''
  1. Assign result to new local variable (or field)

CA also provides a function to assign the function return results to new internal variables. Take the callmethod function as an example, move the cursor to the. callmethod () line to activate CA.

def method (self, a): a.callMethod()

Select assign to field (self, callmethod) or assign to local (callmethod. the callmethod () result is assigned to the new internal variable self. callmethod. The changed code is as follows.

def method (self, a): self.callMethod = a.callMethod()
  1. Assign parameters to attributes

If you need to assign function parameters to variables during program editing, you can use the assign parameters to attributes function of CA to automatically complete this requirement. Move the cursor to the row where function M1 is located and activate CA.

class Foo(object): Def m1(self, a, b):

Select "Assign parameters to attributes" in the label bar and generate two lines of code to assign parameters A and B to variables with the same name.

class Foo(object): def m1(self, a, b):  self.a = a  self.b = b
  1. Surround code with try... try t or try... finally

For code that may generate exceptions, exception capture is usually performed using try... try t or try... finally statements to catch exceptions. Select a piece of code print usage and activate CA's "surround code with try... try t or try... finally" function to automatically capture print usage exceptions.

import sysdef method (self, usage):   try:       print usage   except:       raise

Next, we will introduce how ca functions in pydev extensions are applied.

  • CA function of pydev Extension
  1. Make import for undefined token

Taking the following code as an example, xmlreader is undefined and syntax analysis fails.

class Test: def method(self):      xmlreader

Move the mouse to the error line, press Ctrl + 1 to activate CA, and select "Import xmlreader (XML. ", automatically generate a line of code from XML. sax import xmlreader to eliminate syntax errors.

from xml.sax import xmlreader  class Test: def method(self):      xmlreader
  1. Ignore Error

The above code is still used as an example. Because xmlreader is not defined and contains syntax errors, activate CA in this line and select "undefinedvariable". The syntax error is ignored, xmlreader automatically generates a line of comment indicating "# @ undefinedvariable ".

class Test: def method(self):      xmlreader #@UndefinedVariable
  1. Don't analyze Module

The syntax analyzer can help display code that contains syntax errors. However, during program editing, you sometimes need to deliberately cancel the syntax analysis of the program, the don't analyze module of CA provides this function.

Move the cursor to the first line of the program, activate CA, and select "@ pydevcodeanalysisignore" to automatically generate a line of code "# @ pydevcodeanalysisignore", ignoring the syntax analysis of the program body.

#@PydevCodeAnalysisIgnore   class Test: def method(self):            xmlreader
  1. Quick outline

For a specific Python file, the quick outline provided by pydev extensions can obtain the organizational structure of the file in the simplest and quickest way, and can conveniently query and locate the required information in the file.

In the pydev perspective, select Source-> show quick outline, or press Ctrl + O to start the function.

The organization architectures of Python files such as classes and functions are displayed in a tree. At the same time, the filter provides the query and positioning function to conveniently query the required information and locate the corresponding code segment.

Figure 8. Quick outline

  1. Globals Browser

Globals browser is another powerful query and positioning function provided by pydev extensions. It can query and locate some definitions and attributes of the entire project, including:

    • Class Definition
    • Method Definition
    • Global Variables
    • Class and instance attributes

You can enable this function in three ways.

  • In the pydev perspective, select pydev-> globals browser from the menu bar.

Figure 9. Start globals browser in the menu bar

  • In the pydev perspective, the toolbar has the following small icon. move the cursor over the icon and display the "pydev: globals Browser" annotation. Click this icon to enable the globals browser function.

Figure 10. Start globals browser in the toolbar

  • Press Ctrl + Shift + T to quickly start the globals browser function.

Enter the definition, variable, or attribute to be queried in the filter. globals browser can quickly locate the corresponding code segment.

Figure 11. globals Browser

  1. Hierarchy view

When a python file contains multiple classes, how can we easily and intuitively understand the dependencies between classes? Hierarchy view provides this function, which intuitively displays the hierarchical relationships between multiple classes in a tree structure.

Taking a piece of Python code as an example, four classes are defined: super1, super2, toanalyze, and sub1. In the pydev perspective, choose windows> show View> other. In the displayed show View window, select pydev> hierarchy view. Press the shortcut key F4 to activate hierarchy view. The hierarchy between classes is displayed in the tree chart.

Figure 12. display the class hierarchy in hierarchy view

Hierarchy view also supports the following four features:

  • In the hierarchy chart, click a class, and the method of the class is displayed below the diagram.
  • If you double-click a class, method, or attribute, the source program is called up to edit the class, method, or attribute.
  • In hierarchy view, right-click the hierarchy chart and move the mouse left or right.
  • In hierarchy view, press and hold the left mouse button to move the mouse, and the hierarchy chart is dragged to the corresponding position at will.


Back to Top

Run and debug

Run the program

Two methods are available to run the Python source program. The following uses a code example. py as an example to describe the two running methods.

  • Double-click example. py in pydev package explorer and choose run> Run as> Python run. The program example. py is run immediately and the execution result of the program is displayed on the console.

Figure 13. Python program and running result

  • In pydev package explorer, right-click example. py and choose run as> Python run from the shortcut menu. Similarly, example. py is executed, and the execution result of the program is displayed on the console.

The above two methods are the basic methods for running the source program. Pydev also provides a unique run as Python coverage for the source program. This function not only shows the running results of the program, but also shows the code coverage during the running process.

To view the code coverage, you must first open the code coverage results view. In the pydev perspective, choose windows> show View> code coverage results view. In the left column of the pop-up view, you can see three buttons, "Choose Dir !", "Clear Coverage Information !" And "Refresh coverage infomation ".

Figure 14. code coverage results View

Left click "choose Dir !", In the pop-up folder selection window, select the package of the program to be run and click OK. In this way, all the source programs in this package are displayed in the left column.

Next, we will take example. py as an example to see the results of the run as Python coverage function. Select Run as-> Python coverage. The running result of the program is displayed on the console. Switch to the code coverage results view, and click example. py in the left column.

Figure 15. Show code coverage in code coverage results View

The coverage during code running is clearly displayed in the right column.

Double-click example. py in the left column. The code that is not overwritten is marked with a striking error mark in the editor.

Figure 16. Show unoverwritten code with an error mark

If the code coverage results view is disabled, the overwrite information of the Code is not lost. You can view this information again. Only by clicking "Clear Coverage Information!" in the left column !" To clear the overwrite information after the program runs.

Debug program

Debugging is essential in the process of program development. Mastering debugging skills is the prerequisite and basis for developers to conduct efficient development. The following uses example. py as an example to describe how to use the debugging function of pydev.

Debugging starts with adding a breakpoint. You can set a breakpoint in three ways.

  • Double-click the gray bar on the left of the ruler bar in the editor to add a breakpoint in a line.

Figure 17. Double-click the gray bar on the left of the ruler bar to add a breakpoint

  • Right-click the ruler bar and choose add breakpoint from the menu bar to add a breakpoint.

Figure 18. Right-click the ruler bar to add a breakpoint

  • Move the cursor to the line of code to add a breakpoint, press Ctrl + F10, and select "add breakpoint" in the pop-up menu bar to add a breakpoint.

After adding a breakpoint, select debug as-> Python run to start the debugger. A dialog box is displayed, asking whether to switch to the debugger perspective. Click Yes to display the debugging mode.

Figure 19. Debugger perspective

Frequently Used shortcut keys during program debugging are as follows:

  • One-Step Jump into step into: F5
  • Skip step over: F6 in one step
  • Return step return: F7 in one step
  • Resume: F8

On the console, the execution result of the code before the breakpoint is displayed. To view the value of a variable, take variable A as an example, you can manually type a line of code "Print 'a is: ', a" in the console and press ENTER twice in a row, that is, the value of the variable is displayed.

Figure 20. Variable values displayed on the console

In debug mode, you can view the expression value, right-click the expression, and select watch. The expression panel is displayed, showing the corresponding variable or expression value.

Figure 21. expression value displayed on the Expression panel

If you want to enable the resumable upload to be valid only when certain conditions are met, you can set the resumable upload attribute. Right-click the ruler bar of the editor and select breakpoint properties in the pop-up menu bar. In the displayed window, select the check box "enable condition", enter the conditions to be met, and click OK.

Figure 22. Set the breakpoint attribute

In this way, when you re-execute the program debugging, the breakpoint is valid only when the conditions are met.



Back to Top

Summary

Pydev, combined with ecplise, implements such a powerful and easy-to-use Python ide. This article does not cover all of them and does not provide a detailed description of some basic functions, it highlights some features unique to pydev. The emergence of pydev for eclipse provides good conditions for python developers to achieve efficient project development. This project is also evolving and its functions will become more and more powerful.

References

  • Python topics include the cute Python series, Python Exploration Series, Python extensions, and various application development using python.
  • View the "Eclipse recommended books list ".
  • Browse all eclipse content on developerworks.
  • Are you new to eclipse? Read the developerworks article "getting started with the eclipse platform" to learn about its origins and architecture and how to use plug-ins to expand eclipse.
  • View Eclipse project resources on IBM developerworks to improve your eclipse skills.
  • Visit the open source code area on developerworks for a wide range of how-to information, tools, and project updates to help you develop with open source technology and use it with IBM products.

About the author

Zheng Weifang is currently engaged in clearcase automated testing in the IBM Rational department.

From: http://hi.baidu.com/ma7226087/blog/item/1bd75ad6c815042307088bb1.html from: http://apps.hi.baidu.com/share/detail/21240572

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.