LoginSignup
2
3

More than 5 years have passed since last update.

Google Cloud Functions(The Python Runtime)のHTTP Functionsのテストを書く

Posted at

経緯

Python RuntimeのGoogle Cloud Functions(beta)で画像処理するAPI作ってたのだが、Pythonの場合、Cloud Functions Node.js Emulatorのようなものがまだないので毎回デプロイしないと動作確認できないのが辛かったので、テスト書く方法を模索してみた。

テスト対象コード

公式チュートリアルから拝借。

main.py
def hello_http(request):
    request_json = request.get_json()
    if request_json and 'message' in request_json:
        name = request_json['message']
    else:
        name = 'World'
    return 'Hello, {}!'.format(name)

テストコード

今回はTesting Flask Applicationsを参考にpytestで作成。

テストコード内でflaskのアプリケーション作って、cloud functionsのメソッドを間接的に呼び出すルーティングをして、テストでそれを呼び出すことでflaskっぽい感じのテストをかけるようにした。

test_main.py
import os
import pytest
from flask import Flask
from flask import request
from main import hello_http


@pytest.fixture(scope='session', autouse=True)
def client():
    # setup
    app = Flask(__name__)

    # 間接的にhello_httpを呼び出す
    @app.route("/")
    def _hello_http():
        return hello_http(request)

    client = app.test_client()

    yield client

    # teardown

def test_hello_world(client):
    rv = client.get('/')
    assert b'Hello, World!' in rv.data

def test_hello_yamada(client):
    rv = client.get('/', json={
        'message': 'yamada'
    })
    assert b'Hello, yamada!' in rv.data

参考

雑記

node.js貧民であるのでcloud functionsの処理が書きづらいなーと思ってたところにpython対応(beta)が入ったので、だいぶ書きやすくなって嬉しい。

今の所、大きなバグには遭遇してないので簡単なAPI作るにはとても良さそう。

ただ、flaskベースだけどflaskのルーティングとかのやり方がそのまま使えないのが結構混乱する。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3