Ich habe es mit einem Befehl wie "buster static" geschrieben, in der Hoffnung, einen Webserver zum Testen und Debuggen einzurichten. Wirf dieses Skript in ein Verzeichnis, in dem sich PYTHONPATH befindet.
python -m mocha_server lib/*.js test/*.js
Starten Sie den Webserver im aktuellen Verzeichnis mit.
Zum Ausführen benötigen Sie ein Framework namens python2 (3 ist nicht möglich) und 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