[JAVA] Web server for browser testing with Mocha

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

Web server for browser testing with Mocha
WEB scraping with Python (for personal notes)
Dockerfile for RESTful MeCab server with mecab-ipadic-neologd
[For beginners] Try web scraping with Python
Python Web Content made with Lolipop cheap server
Start a simple Python web server with Docker
Launch a web server with Python and Flask
Data analysis for improving POG 1 ~ Web scraping with Python ~
Created with python GAE DataStore id for testing purposes
HTTP server and HTTP client using Socket (+ web browser) --Python3
Tftp server with Docker
Techniques for code testing?
Web server construction commentary
One Liner Web Server
Ubuntu (18.04.3) Web server construction
Proxy server with Docker
Testing Elasticsearch with python-tcptest
Merry Christmas web server
Local server with python
Set up a web server with CentOS7 + Anaconda + Django + Apache
Build a speed of light web API server with Falcon
When you access the web server, L Chika with Arduino
(For beginners) Try creating a simple web API with Django
Library for specifying a name server and dig with python
Let's reduce the man-hours required for server setup with Ansible
Aggregate the number of hits per second for one day from the web server log with Python
Output the result of morphological analysis with Mecab to a WEB browser compatible with Sakura server / UTF-8