LoginSignup
5
4

More than 5 years have passed since last update.

MochaでブラウザテストをするためのWebサーバ

Last updated at Posted at 2013-03-25

buster staticのようにコマンドで、テストやデバッグ用のWebサーバが立てられるといいなと思って書きました。このスクリプトをPYTHONPATHが通っているディレクトリに放り込んでおき、
python -m mocha_server lib/*.js test/*.js
でカレントディレクトリでWebサーバを起動させます。
実行するには、python2(3は不可)とFlaskというフレームワークが必要です。

mocha_server.py
#!/usr/bin/env python
# coding: utf-8
"""
Mocha server

usage:
    $ python mocha_server.py lib/*.js test/*.js
    or
    $ python -m mocha_server lib/*.js test/*.js
"""
PORT = 8008

import sys
import os
import urllib
import threading
import mimetypes
import flask
from flask import Flask, g, request, render_template_string, abort


sources = []

libs = {
    "/lib/jquery.js": "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",
    "/lib/mocha.js": "https://raw.github.com/visionmedia/mocha/master/mocha.js",
    "/lib/chai.js": "https://raw.github.com/chaijs/chai/master/chai.js",
    "/lib/mocha.css": "https://raw.github.com/visionmedia/mocha/master/mocha.css",
}

app = flask.Flask(__name__)


def main():
    try:
        sources[:] = [s.decode("utf-8") for s in sys.argv[1:]]
    except ValueError:
        sources[:] = [s.decode("shift_jis") for s in sys.argv[1:]]
    sources.sort(key=is_test)

    threads = []
    for lib in libs:
        t = threading.Thread(target=load_worker, args=[lib])
        t.daemon = True
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    app.run(port=PORT, debug=True)


def load_worker(libname):
    source = urllib.urlopen(libs[libname]).read()
    libs[libname] = source


def is_test(source):
    return os.path.basename(source).startswith("test") or \
           "test" in source.split(os.sep)


@app.route("/")
def index():
    return template.render(sources=sources, libs=libs.keys())


@app.route("/lib/<path:p>")
def lib(p):
    if request.path not in libs:
        abort(404)
    mime, _ = mimetypes.guess_type(request.path)
    return flask.Response(libs[request.path], mimetype=mime)


@app.route("/source")
def source_file():
    source = request.args["source"]
    if source not in sources or not os.path.exists(source):
        abort(404)
    mime, _ = mimetypes.guess_type(source)
    return flask.Response(open(source).read(), mimetype=mime)


template = app.jinja_env.from_string("""\
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>mocha sample</title>
        {%- for lib in libs %}
        {%- if lib.endswith("css") %}
        <link href="{{ lib }}" rel="stylesheet">
        {%- else %}
        <script src="{{ lib }}"></script>
        {%- endif %}
        {%- endfor %}
        <script>
            mocha.setup("bdd");
            $(window).load(function() {
                mocha.run()
            });
        </script>
    </head>
    <body>
        <div id="mocha"></div>
        {%- for source in sources %}
        {%- if source.endswith("css") %}
        <link href="{{ url_for("source_file", source=source) }}" rel="stylesheet">
        {%- else %}
        <script src="{{ url_for("source_file", source=source) }}"></script>
        {%- endif %}
        {%- endfor %}
    </body>
</html>""")


if __name__ == '__main__':
    main()

5
4
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
5
4