I wrote it with the hope that a web server for testing and debugging can be set up with a command like buster static
. Throw this script into a directory that PYTHONPATH is in,
python -m mocha_server lib/*.js test/*.js
Start the web server in the current directory with.
To run it, you need a framework called python2 (3 is not possible) and 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()
Recommended Posts