Payon
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # pytest與flask ###### tags: `unit-test` `pytest` `flask` ## 序言 在之前的幾篇隨筆中,各位應該不難發現,在測試進行時,我們需要import被測試的module,畢竟要測試一個函式的功能,首先得先把他抓出來吧。 但如果今天被測試的對象是一個Flask的API呢? ```python= @app.route('/login', methods=['GET', 'POST']) def login(): # 簡單的登入實作,get時給登入頁的html,post時驗證輸入的帳號密碼 if request.method == 'POST': # 取得使用者輸入的帳號和密碼 username = request.form['username'] password = request.form['password'] # 檢查帳號和密碼是否正確 if check_credentials(username, password): g.current_user = 'admin' return "登入成功" else: return "登入失敗" else: # 顯示登入表單 return render_template('login.html') ``` 想像我們現在有個運行中的Flask,手動測試的話我們會使用postman或curl打API,測試不同的輸入/form/headers會不會對API輸出造成影響,那今天我們要寫一個這樣的測試是不是要寫一個script跑postman呢? ## Flask的test_client 當然不是,因為flask提供了一個test_client的類別,首先我們有一個已經建立起的Factory method: ```python= # factory.py from flask import Flask def create_app(): app = Flask(__name__) return app ``` 在main.py中,要連接這個factory method會這樣寫: ```python= from my_project import create_app app = create_app() if __name__ == '__main__': app.run('0.0.0.0', port=5000) ``` 而在測試的流程中,我們可以用同樣的方式,但換成test_client: ```python= import pytest from my_project import create_app @pytest.fixture() def app(): app = create_app() app.config.update({ "TESTING": True, }) # setup if you need, and yield the app, make test_client open during test yield app # clean up / reset resources here @pytest.fixture() def client(app): return app.test_client() ``` 注意這邊使用pytest的fixture,可以讓我們在撰寫測試時直接在測試中調用client來用: ```python= def test_request_example(client): response = client.get("/posts") assert b"<h2>Hello, World!</h2>" in response.data ``` 這樣的寫法就可以讓我們直接對api做測試,在流程上就簡化了許多。 ## 參數詳細解釋 test_client主要有幾個常用到的參數,都以dict的形式給予: * query_string : 當API有需要再uri後續在?後的參數時使用,例如/users?id=12321 * headers : 當call的API需要headers時使用,例如需要將認證token放置在headers中的API * data : 當需要上傳檔案時可以使用,會自動幫你把headers中的Content-type設定成multipart/form-data * json : 送json body用的,會自動把Content-type設定成application/json 更多參數設定可以參考 https://flask.palletsprojects.com/en/2.3.x/testing/ ## 其他進階問題 **Q. 為什麼要用yield?** **A.** 因為要讓整個測試過程停留在看得到flask的狀態,包含g/session/reqeust等等flask的參數都可以被測試看到,如果用return當然也可以過,但就只看得到回傳回來的Response object **Q. 我可不可以在測試中直接設定flask.g? 比如設定g.user="test"給某個測試用** **A.** 可以用比較不直覺的方式拿到,首先要理解要修改g或session要手動把app_context或request_context打開...(下略2000字,這之後會是一篇文,大概),但簡單來說就是這樣幹 ```python= @pytest.fixture() def pre_test_client(): app = create_app() # 打開 test_client with app.test_client() as test_client: # 打開 application context with app.app_context(): # 現在在測試以外的地方也可以操控g跟create_app了 yield test_client ``` ## 結語 不知不覺也拖稿了一陣子,但好歹是把基礎的pytest/flask相關的簡單用法講完了,希望各位經過以上的文章可以了解用法,並基於自己需要測試的flask api進行修改。 至於flask的app context跟request context是怎麼設計,為什麼我們只要打開就可以設定g就留給之後的文章進行說明吧。 老樣子希望各位的專案與測試都進行的順利,我們下次見。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully