Flask_ Unit Test

Source: Internet
Author: User

We can now try to add a user to the database at the console:

IN[2]: Import model;in[3]: From microblog import db;in[4]: U=model. User (nickname= "wll", email= "[email protected]"); In[5]: Db.session.add (U); in[6]: Db.session.commit ();

Next we run the program, we will use the previous user login, log in and then change his user name to WLL, see what happens after the program is running error:

This is what we will find on the browser page just to report the server internal error. We have no way of knowing exactly where the program went wrong. This is what we do not want to see during the development process. At this point we can try to get our application to run in debug mode. Debug mode is when the application runs by passing parameters in the Run method debug = True.

Now we continue to run the program: (Change the user name to the same name as the previously added user)

We can see that the server internal error is not reported, but the specific error message is displayed:

From this message we can clearly see that it is a violation of the unique constraint.

But we do not want our users to be able to see the internal error of the program, we only have to set debug to False. But now there are two more problems: the first one is appearance: The default 500 error page is ugly. The second small problem is quite important. We may not know when the user will encounter a failure in our program because debugging is now disabled. Fortunately there are two simple ways to solve these two problems.

One, custom HTTP error handler:

Flask provides a mechanism for applications to install their own error pages. As an example, let's customize the HTTP 404 and 500 error pages, which is the most common of the two. Other errors are defined in the same way. In order to declare a custom error handler, you need to use the adorner errorhandler (file microblog.py):

@app. ErrorHandler (404) def internal_error (Error):    return render_template (' 404.html '), 404@app.errorhandler (500 ) def internal_error (Error):    db.session.rollback ()    return render_template (' 500.html '), 500

The above does not need to explain more, the code is clear, the only interesting is in the error 500 processor in the rollback declaration. This is necessary because this function is called as the result of an exception. If the exception is triggered by a database error, the session of the database is in an unhealthy state, so we must roll back the session to normal working state before rendering the 500 error page template.

404 Error Template: (templates/404.html)

{% extends "base.html"%}{% block content%} < H1 > File not Found</H1><p><href  = "{{url_for (' Index ')}}">back</a></ P > {% Endblock%}

500 error Template: (templates/500.html)

{% extends "base.html"%}{% block content%}<H1>An unexpected error had occurred</H1><P>The administrator has been notified. Sorry for the inconvenience!</P><P><ahref= "{{url_for (' Index ')}}">Back</a></P>{% Endblock%}

Ii. Sending errors via email

To solve our second problem, we will configure two application error reporting mechanisms. The first is to send an email when the error occurs.

Before we begin, we will first configure the mail server and the Administrator email address (file config.py) in the application:

# mail server settingsmail_server = ' localhost ' mail_port = 25mail_username = Nonemail_password = none# Administrator ListA Dmins = [' [email protected] ']

Flask uses the Python logging module, so it's easy to send messages when an exception occurs (microblog.py)

From config import basedir,admins,mail_server,mail_port,mail_username,mail_passwordif not app.debug:    Import Logging from    logging.handlers import smtphandler    credentials = None    if Mail_username or Mail_password:         credentials = (Mail_username, mail_password)    Mail_handler = Smtphandler ((mail_server, Mail_port), ' [email Protected] ' + mail_server, ADMINS, ' microblog failure ', credentials)    mail_handler.setlevel (logging. ERROR)    App.logger.addHandler (Mail_handler)

It is fairly easy to test the above code on a development machine without a mail server, thanks to the Python SMTP debug server. Just open a new command-line window (Windows users open a command prompt) and then run the following to open a fake mailbox server:

We will close the debug mode in the program (DEBUG=FALSE), we will see the specific error at the command prompt: (as shown in:)

Third, record to file

Receiving errors via mail is good, but sometimes that's not enough. Some failures do not end with exceptions and are not major problems, but we may want to track them in the logs for some debugging.

For this reason, we also want to keep a log file for the application.

Enabling logging is similar to sending an e-mail error (file microblog.py):

If not app.debug:    import logging from    logging.handlers import rotatingfilehandler    File_handler = Rotatingfilehandler (' Tmp/microblog.log ', ' a ', 1 * 1024x768 * 1024x768, Ten)    File_handler.setformatter (logging. Formatter ('% (asctime) s% (levelname) s:% (message) s [in% (pathname) s:% (Lineno) d] '))    app.logger.setLevel (logging. INFO)    file_handler.setlevel (logging.info)    App.logger.addHandler (File_handler)    app.logger.info (' Microblog startup ')

The log file will be in the tmp directory with the name Microblog.log. We use Rotatingfilehandler so that the size of the log generated is limited. In this example, our log file size is limited to 1 megabytes, and we will keep the last 10 log files as backups.

logging. The Formatter class is capable of customizing the format of log information. Since this information is recorded in a file, we want them to provide as much information as possible, so we write a timestamp, the logging level and the message origin as well as the log message and the file and line number of the stack trace.

To make the log more useful, we lowered the application log and the level of the file log processor, giving us the opportunity to write helpful information to the log, not necessarily when the error occurred. From then on, every time you start a useful program in non-debug mode, the log logs events.

While we will not have a lot of recorder requirements at this time, debugging a Web server that is online and in use is very difficult. Message logging to a file is a very useful tool in diagnosing and locating problems, so we are now ready and we need to use this feature.

Below we test, we still edit the same error, the user name to the database already exists user's name, we can see the TMP folder more than a Microblog.log file, the file content is as follows:

2016-11-01 11:06:27,548 info:microblog startup [in C:\users\wls003\pycharmprojects\microblog_study\microblog.py:30] 2016-11-01 11:06:27,595 info:microblog startup [in microblog.py:30]2016-11-01 11:06:51,341 error:exception on/edit [POS T] [in C:\users\wls003\anaconda2\lib\site-packages\flask\app.py:1423]traceback (most recent): File "C:\Users  \wls003\anaconda2\lib\site-packages\flask\app.py ", line 1817, in Wsgi_app response = Self.full_dispatch_request () File "C:\Users\wls003\Anaconda2\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request RV = Self.handle_user _exception (E) File "C:\Users\wls003\Anaconda2\lib\site-packages\flask\app.py", line 1381, in Handle_user_exception re Raise (Exc_type, Exc_value, TB) File "C:\Users\wls003\Anaconda2\lib\site-packages\flask\app.py", line 1475, in Full_ Dispatch_request RV = self.dispatch_request () File "C:\Users\wls003\Anaconda2\lib\site-packages\flask\app.py", line 1 461, in Dispatch_request return SELF.VIEw_functions[rule.endpoint] (**req.view_args) File "C:\Users\wls003\Anaconda2\lib\site-packages\flask_login.py",   Line 758, in Decorated_view return func (*args, **kwargs) File ' microblog.py ', line 122, in edit db.session.commit () File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\orm\scoping.py", line 157, in Do return GetAttr (Self.reg Istry (), name) (*args, **kwargs) File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\orm\session.py", line 801, in Commit self.transaction.commit () File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\orm\ session.py ", line 392, in commit self._prepare_impl () File" C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\or m\session.py ", line 372, in _prepare_impl Self.session.flush () File" C:\Users\wls003\Anaconda2\lib\site-packages\sqla lchemy\orm\session.py ", line 2019, in Flush Self._flush (objects) File" C:\Users\wls003\Anaconda2\lib\site-packages\sq lalchemy\orm\session.py ", line 2137, in _flush TranSaction.rollback (_capture_exception=true) File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\util\ langhelpers.py ", line Max, in __exit__ compat.reraise (Exc_type, Exc_value, EXC_TB) File" C:\Users\wls003\Anaconda2\lib\ site-packages\sqlalchemy\orm\session.py ", line 2101, in _flush flush_context.execute () File" C:\Users\wls003\Anaconda 2\lib\site-packages\sqlalchemy\orm\unitofwork.py ", line 373, in execute Rec.execute (self) File" C:\Users\wls003\Anaco nda2\lib\site-packages\sqlalchemy\orm\unitofwork.py ", line 532, in execute UOW File" C:\Users\wls003\Anaconda2\lib\si te-packages\sqlalchemy\orm\persistence.py ", line-save_obj, in-Mapper, table, update) File" C:\Users\wls003\Anacond a2\lib\site-packages\sqlalchemy\orm\persistence.py ", line 706, in _emit_update_statements execute (statement, Multiparams) File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\engine\base.py", line 914, in execute retur n Meth (self, multiparams, params) File "C:\Users\wls003\anaconda2\lib\site-packages\sqlalchemy\sql\elements.py ", line 323, in _execute_on_connection return connection . _execute_clauseelement (self, multiparams, params) File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\ engine\base.py ", line 1010, in _execute_clauseelement compiled_sql, Distilled_params File" C:\Users\wls003\Anaconda2\l ib\site-packages\sqlalchemy\engine\base.py ", line 1146, in _execute_context context) File" C:\Users\wls003\Anaconda2\ lib\site-packages\sqlalchemy\engine\base.py ", line 1341, in _handle_dbapi_exception exc_info File" C:\Users\wls003\An aconda2\lib\site-packages\sqlalchemy\util\compat.py ", line $, in Raise_from_cause reraise (Type (Exception), Exception, TB=EXC_TB, Cause=cause) File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\engine\base.py", Line 1139, in _execute_context context) File "C:\Users\wls003\Anaconda2\lib\site-packages\sqlalchemy\engine\ default.py ", line Do_execute cursor.execute (statement,Parameters) Integrityerror: (Sqlite3. Integrityerror) UNIQUE constraint failed:user.nickname [sql:u ' UPDATE user SET nickname=?, about_me=? WHERE user.id =? '] [Parameters: (U ' wll ', U ' hello,my name is Ninicwang!!! ', 1)]

Iv. Fix bugs

Now let's solve the problem of nickname repetition.

As discussed earlier, there are currently two places where there is no processing duplication. The first one is in the after_login function. When a user successfully logs in to the system this function is called, where we need to create a new user instance. Here is the affected code block (file microblog.py):

    If user is none:        nickname = Resp.nickname        if nickname is None or nickname = = "":            nickname = Resp.email.split (' @ ') [0]        nickname = model. User.make_unique_nickname (nickname)        user = model. User (Nickname=nickname, email=resp.email)        db.session.add (user)        Db.session.commit ()

The way to solve the problem is to have the User class choose a unique name for us. This is what the new Make_unique_nickname method does (file model.py):

@staticmethod    def make_unique_nickname (nickname):        if User.query.filter_by (Nickname=nickname). First () = = None:            return nickname        Version = 2 while        True:            new_nickname = nickname + str (version)            if User.query.filter_by (Nickname=new_nickname). First () = = None: Break            Version + = 1        return new_nickname

This method simply adds a counter to the requested nickname until a unique name is found. For example, if the user name "Miguel" already exists, this method will suggest "Miguel2", if this is still present, it will be recommended to use "Miguel3", go down until you find a unique user name. It is important to note that we use this method as a static method because this operation does not apply to instances of any particular class.

The second problem with duplicate nicknames is the view function that edits user information. This is slightly more difficult to deal with because this is the user's own choice of nickname. The right thing to do is not to accept a duplicate nickname and let the user reenter one. We will address this problem by adding a custom validation of the nickname form field. If the user enters an illegal nickname, the validation of the field will fail and the user will be returned to the Edit user Information page. To add validation, we only need to override the form's validate method (file form.py):

Class EditForm (Form):    nickname = Stringfield (' nickname ', validators=[datarequired ()])    About_me = Textareafield (' About_me ', Validators=[length (min=0, max=140)])    def __init__ (self, original_nickname, *args, * * Kwargs):        form.__init__ (self, *args, **kwargs)        self.original_nickname = Original_nickname    def validate ( Self):        if isn't form.validate (self):            return False        if self.nickname.data = = Self.original_nickname:            Return True to        user =model. User.query.filter_by (Nickname=self.nickname.data). First ()        if user! = None:            self.nickname.errors.append ( ' This nickname are already in use. Please choose another one. ')            Return False        return True

The initialization of the form has a new parameter, original_nickname. The validate method uses it to determine when a nickname has changed. Accept it if no changes have occurred. If changes have occurred, make sure that the nickname is unique in the database.

This parameter is passed in the view:

@app. Route ('/edit ', methods=[' GET ', ' POST ') @login_requireddef edit (): From    model Import db    form = EditForm ( G.user.nickname)

In order to complete this modification, we must make the field error message appear in the form template (file templates/edit.html):

<TD>Your Nickname:</TD><TD>{{Form.nickname (size = +)}} {% for error in form.errors.nickname%}<BR><spanstyle= "color:red;">[{{error}}]</span>{% ENDFOR%}
</TD>

Now let's test the results:

V. Unit Testing Framework

As the size of the application becomes larger, the more difficult it is to ensure that code modifications do not affect existing functionality.

The traditional way – regression testing is a good idea. You write tests to verify all the different features of the application. Each test focuses on a single point of concern to verify that the results are not expected. Perform regular tests to ensure that the application works as expected. When the test coverage is large, by running the test you have the confidence to ensure that the modification and new points do not affect the application.

We use the Python unittest module to build a simple test framework (file tests.py):

1 #!flask/bin/python2 Import OS3 Import UnitTest4 From config import basedir5 From microblog import app,db6 class TestCase (unittest. TestCase):7 def setUp (self):8 app.config[' testing ') = True9 app.config[' wtf_csrf_enabled ' = FalseTen app.config[' sqlalchemy_database_uri ' = ' sqlite:///' + os.path.join (basedir, ' test.db ') One Self.app = app.test_client () A Db.create_all () - def tearDown (self): - Db.session.remove () the Db.drop_all () - def test_make_unique_nickname (self): - From model import User - u = User (nickname= ' John ', email= ' [email protected] ') + db.session.add (U) - Db.session.commit () + nickname = User.make_unique_nickname (' john ') A assert Nickname! = ' John ' at u = User (nickname=nickname, email= ' [email protected] ') - db.session.add (U) - Db.session.commit () - nickname2 = User.make_unique_nickname (' john ') - assert nickname2! = ' John ' - assert nickname2! = Nickname in  - if __name__ = = ' __main__ ': toUnittest.main ()

Our tests are included in the TestCase class. The setUp and TearDown methods are special, and they run before and after testing, respectively. (Some configuration was made in setUp to reset the contents of the database in tearDown .) )

Run: Python test.py

Flask_ Unit Test

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.