chantra / rpms / librepo

Forked from rpms/librepo 2 years ago
Clone

Blame SOURCES/0001-Replace-python3-flask-with-httpserver-in-python-tests.patch

936122
From 8bba792da37142028f6b6e61137ec2988b5578ee Mon Sep 17 00:00:00 2001
936122
From: Pavla Kratochvilova <pkratoch@redhat.com>
936122
Date: Mon, 26 Apr 2021 09:42:15 +0200
936122
Subject: [PATCH] Replace python3-flask with http.server in python tests
936122
936122
---
936122
 README.md                                          |   1 -
936122
 librepo.spec                                       |   1 -
936122
 tests/README.rst                                   |  36 ++++++++++--------------------------
936122
 tests/python/tests/base.py                         |  24 ++++--------------------
936122
 tests/python/tests/servermock/server.py            |  31 +++++++++----------------------
936122
 tests/python/tests/servermock/yum_mock/yum_mock.py | 279 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------
936122
 tests/python/tests/test_yum_package_downloading.py |   9 +++------
936122
 tests/python/tests/test_yum_repo_downloading.py    |   5 ++---
936122
 8 files changed, 175 insertions(+), 211 deletions(-)
936122
936122
diff --git a/README.md b/README.md
936122
index ad6bc23..d9fb062 100644
936122
--- a/README.md
936122
+++ b/README.md
936122
@@ -19,7 +19,6 @@ Fedora/Ubuntu name
936122
 * openssl (http://www.openssl.org/) - openssl-devel/libssl-dev
936122
 * python (http://python.org/) - python3-devel/libpython3-dev
936122
 * **Test requires:** pygpgme (https://pypi.python.org/pypi/pygpgme/0.1) - python3-pygpgme/python3-gpgme
936122
-* **Test requires:** python3-flask (http://flask.pocoo.org/) - python-flask/python-flask
936122
 * **Test requires:** python3-pyxattr (https://github.com/xattr/xattr) - python3-pyxattr/python3-pyxattr
936122
 
936122
 ### Build from your checkout dir:
936122
diff --git a/librepo.spec b/librepo.spec
936122
index 6db1fc2..ed90a84 100644
936122
--- a/librepo.spec
936122
+++ b/librepo.spec
936122
@@ -51,7 +51,6 @@ Summary:        Python 3 bindings for the librepo library
936122
 %{?python_provide:%python_provide python3-%{name}}
936122
 BuildRequires:  python3-devel
936122
 BuildRequires:  python3-gpg
936122
-BuildRequires:  python3-flask
936122
 BuildRequires:  python3-pyxattr
936122
 BuildRequires:  python3-requests
936122
 BuildRequires:  python3-sphinx
936122
diff --git a/tests/README.rst b/tests/README.rst
936122
index ea55c87..f7e6d03 100644
936122
--- a/tests/README.rst
936122
+++ b/tests/README.rst
936122
@@ -33,15 +33,13 @@ Files of C tests
936122
  * Test suites
936122
 
936122
 
936122
-Python tests with Flask
936122
-=======================
936122
+Python tests http.server
936122
+========================
936122
 
936122
-Some python tests use **Flask** python framework (http://flask.pocoo.org/)
936122
+Some python tests use **http.server** python standard library
936122
 to simulate web server. The server is started automatically during that tests.
936122
 
936122
-*TestCases with Flask inherit from TestCaseWithApp class.*
936122
-
936122
-The Flask is then set as the app to the test case by 'application' class attribute.
936122
+*TestCases with http.server inherit from TestCaseWithServer class.*
936122
 
936122
 If you want to start server manually::
936122
 
936122
@@ -57,27 +55,13 @@ http://127.0.0.1:5000/yum/badgpg/static/01/repodata/repomd.xml.asc
936122
 
936122
 etc..
936122
 
936122
-Modularity of tests with Flask
936122
-------------------------------
936122
-
936122
-Flask tests are intended to be modular.
936122
-
936122
-Modularity is provided by use of http://flask.pocoo.org/docs/blueprints/
936122
-Currently there is only one module (blueprint) for yum repo mocking
936122
-in servermock/yum_mock.
936122
-
936122
-Repos for test with Flask
936122
--------------------------
936122
-
936122
-Currently each module (blueprint) uses its own data (repositories,
936122
-packages, ..).
936122
+Repos for test with http.server
936122
+-------------------------------
936122
 
936122
-E.g. for yum mocking module: servermock/yum_mock/static/
936122
+All data (repositories, packages, ..) are in servermock/yum_mock/static/
936122
 
936122
-Configuration and globals for tests with Flask
936122
-----------------------------------------------
936122
+Configuration and globals for tests with http.server
936122
+----------------------------------------------------
936122
 
936122
-Each module (blueprint) has its own configuration and globals which uses
936122
-and provides to tests which use the module.
936122
+Configuration and globals used by these tests are in servermock/yum_mock/config.py
936122
 
936122
-E.g. for yum mocking module: servermock/yum_mock/config.py
936122
diff --git a/tests/python/tests/base.py b/tests/python/tests/base.py
936122
index 1d01c9d..ecabbb5 100644
936122
--- a/tests/python/tests/base.py
936122
+++ b/tests/python/tests/base.py
936122
@@ -5,7 +5,7 @@ import ctypes
936122
 import os.path
936122
 import requests
936122
 from multiprocessing import Process, Value
936122
-from tests.servermock.server import app
936122
+from tests.servermock.server import start_server
936122
 try:
936122
     import unittest2 as unittest
936122
 except ImportError:
936122
@@ -53,39 +53,23 @@ class TestCase(unittest.TestCase):
936122
     pass
936122
 
936122
 
936122
-class TestCaseWithApp(TestCase):
936122
-    application = NotImplemented
936122
-
936122
-    @classmethod
936122
-    def setUpClass(cls):
936122
-        cls.server = Process(target=cls.application.run)
936122
-        cls.server.start()
936122
-        time.sleep(0.5)
936122
-
936122
-    @classmethod
936122
-    def tearDownClass(cls):
936122
-        cls.server.terminate()
936122
-        cls.server.join()
936122
-
936122
-
936122
 def application(port):
936122
     """Sometimes, the port is used, in that case, use different port"""
936122
 
936122
     while True:
936122
         try:
936122
             port_val = port.value
936122
-            app._librepo_port = port_val    # Store used port into Flask app
936122
-            app.run(port=port_val)
936122
-        except socket.error as e:
936122
+            start_server(port=port_val)
936122
+        except OSError as e:
936122
             if e.errno == 98:
936122
                 # Address already in use
936122
                 port.value += 1
936122
                 continue
936122
             raise
936122
         break
936122
 
936122
 
936122
-class TestCaseWithFlask(TestCase):
936122
+class TestCaseWithServer(TestCase):
936122
     _TS_PORT = Value(ctypes.c_int, 5000)
936122
     MOCKURL = None
936122
     PORT = -1
936122
diff --git a/tests/python/tests/servermock/server.py b/tests/python/tests/servermock/server.py
936122
index 6d17a0a..37ddb64 100644
936122
--- a/tests/python/tests/servermock/server.py
936122
+++ b/tests/python/tests/servermock/server.py
936122
@@ -1,42 +1,29 @@
936122
-from flask import Flask
936122
+from http.server import BaseHTTPRequestHandler, HTTPServer
936122
 from optparse import OptionParser
936122
 try:
936122
-    from yum_mock.yum_mock import yum_mock
936122
+    from yum_mock.yum_mock import yum_mock_handler
936122
 except (ValueError, ImportError):
936122
-    from .yum_mock.yum_mock import yum_mock
936122
+    from .yum_mock.yum_mock import yum_mock_handler
936122
 
936122
-app = Flask(__name__)
936122
-#app.register_blueprint(working_repo)
936122
-app.register_blueprint(yum_mock, url_prefix='/yum')
936122
 
936122
+def start_server(port, host="127.0.0.1", handler=None):
936122
+    if handler is None:
936122
+        handler = yum_mock_handler(port)
936122
+    with HTTPServer((host, port), handler) as server:
936122
+        server.serve_forever()
936122
 
936122
 if __name__ == '__main__':
936122
     parser = OptionParser("%prog [options]")
936122
     parser.add_option(
936122
-        "-d", "--debug",
936122
-        action="store_true",
936122
-    )
936122
-    parser.add_option(
936122
         "-p", "--port",
936122
         default=5000,
936122
         type="int",
936122
     )
936122
     parser.add_option(
936122
         "-n", "--host",
936122
         default="127.0.0.1",
936122
     )
936122
-    parser.add_option(
936122
-        "--passthrough_errors",
936122
-        action="store_true",
936122
-    )
936122
     options, args = parser.parse_args()
936122
 
936122
-    kwargs = {
936122
-        "threaded": True,
936122
-        "debug": options.debug,
936122
-        "port": options.port,
936122
-        "host": options.host,
936122
-        "passthrough_errors": options.passthrough_errors,
936122
-    }
936122
+    start_server(options.port, options.host)
936122
 
936122
-    app.run(**kwargs)
936122
diff --git a/tests/python/tests/servermock/yum_mock/yum_mock.py b/tests/python/tests/servermock/yum_mock/yum_mock.py
936122
index 826f7c8..dd5bda6 100644
936122
--- a/tests/python/tests/servermock/yum_mock/yum_mock.py
936122
+++ b/tests/python/tests/servermock/yum_mock/yum_mock.py
936122
@@ -1,137 +1,152 @@
936122
+import base64
936122
+from http.server import BaseHTTPRequestHandler, HTTPServer
936122
 import os
936122
-from flask import Blueprint, render_template, abort, send_file, request, Response
936122
-from flask import current_app
936122
-from functools import wraps
936122
+import sys
936122
 
936122
 from .config import AUTH_USER, AUTH_PASS
936122
 
936122
-yum_mock = Blueprint('yum_mock', __name__,
936122
-                        template_folder='templates',
936122
-                        static_folder='static')
936122
-
936122
-@yum_mock.route('/static/mirrorlist/<path:path>')
936122
-def serve_mirrorlists_with_right_port(path):
936122
-    try:
936122
-        with yum_mock.open_resource('static/mirrorlist/'+path) as f:
936122
-            data = f.read()
936122
-            data = data.decode('utf-8')
936122
-            data = data.replace(":{PORT_PLACEHOLDER}", ":%d" % current_app._librepo_port)
936122
-            return data
936122
-    except IOError:
936122
-        # File probably doesn't exist or we can't read it
936122
-        abort(404)
936122
-
936122
-@yum_mock.route('/static/metalink/<path:path>')
936122
-def serve_metalinks_with_right_port(path):
936122
-    try:
936122
-        with yum_mock.open_resource('static/metalink/'+path) as f:
936122
-            data = f.read()
936122
-            data = data.decode('utf-8')
936122
-            data = data.replace(":{PORT_PLACEHOLDER}", ":%d" % current_app._librepo_port)
936122
-            return data
936122
-    except IOError:
936122
-        # File probably doesn't exist or we can't read it
936122
-        abort(404)
936122
-
936122
-@yum_mock.route('/harm_checksum/<keyword>/<path:path>')
936122
-def harm_checksum(keyword, path):
936122
-    """Append two newlines to content of a file (from the static dir) with
936122
-    specified keyword in the filename. If the filename doesn't contain
936122
-    the keyword, content of the file is returnen unchanged."""
936122
-
936122
-    if "static/" not in path:
936122
-        # Support changing only files from static directory
936122
-        abort(400)
936122
-    path = path[path.find("static/"):]
936122
-
936122
-    try:
936122
-        with yum_mock.open_resource(path) as f:
936122
-            data = f.read()
936122
-            if keyword in os.path.basename(path):
936122
-                return "%s\n\n" %data
936122
-            return data
936122
-    except IOError:
936122
-        # File probably doesn't exist or we can't read it
936122
-        abort(404)
936122
-
936122
-@yum_mock.route("/not_found/<keyword>/<path:path>")
936122
-def not_found(keyword, path):
936122
-    """For each file containing keyword in the filename, http status
936122
-    code 404 will be returned"""
936122
-
936122
-    if "static/" not in path:
936122
-        abort(400)
936122
-    path = path[path.find("static/"):]
936122
-
936122
-    try:
936122
-        with yum_mock.open_resource(path) as f:
936122
-            data = f.read()
936122
-            if keyword in os.path.basename(path):
936122
-                abort(404)
936122
-            return data
936122
-    except IOError:
936122
-        # File probably doesn't exist or we can't read it
936122
-        abort(404)
936122
-
936122
-@yum_mock.route("/badurl/<path:path>")
936122
-def badurl(path):
936122
-    """Just return 404 for each url with this prefix"""
936122
-    abort(404)
936122
-
936122
-@yum_mock.route("/badgpg/<path:path>")
936122
-def badgpg(path):
936122
-    """Instead of <path>/repomd.xml.asc returns
936122
-    content of <path>/repomd.xml.asc.bad"""
936122
-    if "static/" not in path:
936122
-        abort(400)
936122
-    path = path[path.find("static/"):]
936122
-    if path.endswith("repomd.xml.asc"):
936122
-        path = path + ".bad"
936122
-
936122
-    try:
936122
-        with yum_mock.open_resource(path) as f:
936122
-            return f.read()
936122
-    except IOError:
936122
-        # File probably doesn't exist or we can't read it
936122
-        abort(404)
936122
-
936122
-# Basic Auth
936122
-
936122
-def check_auth(username, password):
936122
-    """This function is called to check if a username /
936122
-    password combination is valid.
936122
-    """
936122
-    return username == AUTH_USER and password == AUTH_PASS
936122
-
936122
-def authenticate():
936122
-    """Sends a 401 response that enables basic auth"""
936122
-    return Response(
936122
-    'Could not verify your access level for that URL.\n'
936122
-    'You have to login with proper credentials', 401,
936122
-    {'WWW-Authenticate': 'Basic realm="Login Required"'})
936122
-
936122
-def requires_auth(f):
936122
-    @wraps(f)
936122
-    def decorated(*args, **kwargs):
936122
-        auth = request.authorization
936122
-        if not auth or not check_auth(auth.username, auth.password):
936122
-            return authenticate()
936122
-        return f(*args, **kwargs)
936122
-    return decorated
936122
-
936122
-@yum_mock.route("/auth_basic/<path:path>")
936122
-@requires_auth
936122
-def secret_repo_basic_auth(path):
936122
-    """Page secured with basic HTTP auth
936122
-    User: admin Password: secret"""
936122
-    if "static/" not in path:
936122
-        abort(400)
936122
-    path = path[path.find("static/"):]
936122
-
936122
-    try:
936122
-        with yum_mock.open_resource(path) as f:
936122
-            data = f.read()
936122
-            return data
936122
-    except IOError:
936122
-        abort(404)
936122
+
936122
+def file_path(path):
936122
+    return(os.path.join(os.path.dirname(os.path.abspath(__file__)), path))
936122
+
936122
+
936122
+def yum_mock_handler(port):
936122
+
936122
+    class YumMockHandler(BaseHTTPRequestHandler):
936122
+        _port = port
936122
+
936122
+        def return_bad_request(self):
936122
+            self.send_response(400)
936122
+            self.end_headers()
936122
+
936122
+        def return_not_found(self):
936122
+            self.send_response(404)
936122
+            self.end_headers()
936122
+
936122
+        def return_ok_with_message(self, message, content_type='text/html'):
936122
+            if content_type == 'text/html':
936122
+                message = bytes(message, 'utf8')
936122
+            self.send_response(200)
936122
+            self.send_header('Content-type', content_type)
936122
+            self.send_header('Content-Length', str(len(message)))
936122
+            self.end_headers()
936122
+            self.wfile.write(message)
936122
+
936122
+        def parse_path(self, test_prefix='', keyword_expected=False):
936122
+            path = self.path[len(test_prefix):]
936122
+            if keyword_expected:
936122
+                keyword, path = path.split('/', 1)
936122
+            # Strip arguments
936122
+            if '?' in path:
936122
+                path = path[:path.find('?')]
936122
+            if keyword_expected:
936122
+                return keyword, path
936122
+            return path
936122
+
936122
+        def serve_file(self, path, harm_keyword=None):
936122
+            if "static/" not in path:
936122
+                # Support changing only files from static directory
936122
+                return self.return_bad_request()
936122
+            path = path[path.find("static/"):]
936122
+            try:
936122
+                with open(file_path(path), 'rb') as f:
936122
+                    data = f.read()
936122
+                    if harm_keyword is not None and harm_keyword in os.path.basename(file_path(path)):
936122
+                        data += b"\n\n"
936122
+                    return self.return_ok_with_message(data, 'application/octet-stream')
936122
+            except IOError:
936122
+                # File probably doesn't exist or we can't read it
936122
+                return self.return_not_found()
936122
+
936122
+        def authenticate(self):
936122
+            """Sends a 401 response that enables basic auth"""
936122
+            self.send_response(401)
936122
+            self.send_header('Content-type', 'text/html')
936122
+            self.send_header('WWW-Authenticate', 'Basic realm="Login Required')
936122
+            self.end_headers()
936122
+            message = (
936122
+                'Could not verify your access level for that URL.\n'
936122
+                'You have to login with proper credentials'
936122
+            )
936122
+            self.wfile.write(bytes(message, "utf8"))
936122
+
936122
+        def check_auth(self):
936122
+            if self.headers.get('Authorization') is None:
936122
+                return False
936122
+            expected_authorization = 'Basic {}'.format(
936122
+                base64.b64encode('{}:{}'.format(AUTH_USER, AUTH_PASS).encode()).decode()
936122
+            )
936122
+            if self.headers.get('Authorization') != expected_authorization:
936122
+                return False
936122
+            return True
936122
+
936122
+        def serve_mirrorlist_or_metalink_with_right_port(self):
936122
+            path = self.parse_path()
936122
+            if "static/" not in path:
936122
+                return self.return_bad_request()
936122
+            path = path[path.find("static/"):]
936122
+            try:
936122
+                with open(file_path(path), 'r') as f:
936122
+                    data = f.read()
936122
+                    data = data.replace(":{PORT_PLACEHOLDER}", ":%d" % self._port)
936122
+                    return self.return_ok_with_message(data)
936122
+            except IOError:
936122
+                # File probably doesn't exist or we can't read it
936122
+                return self.return_not_found()
936122
+
936122
+        def serve_harm_checksum(self):
936122
+            """Append two newlines to content of a file (from the static dir) with
936122
+            specified keyword in the filename. If the filename doesn't contain
936122
+            the keyword, content of the file is returnen unchanged."""
936122
+            keyword, path = self.parse_path('/yum/harm_checksum/', keyword_expected=True)
936122
+            self.serve_file(path, harm_keyword=keyword)
936122
+
936122
+        def serve_not_found(self):
936122
+            """For each file containing keyword in the filename, http status
936122
+            code 404 will be returned"""
936122
+            keyword, path = self.parse_path('/yum/not_found/', keyword_expected=True)
936122
+            if keyword in os.path.basename(file_path(path)):
936122
+                return self.return_not_found()
936122
+            self.serve_file(path)
936122
+
936122
+        def serve_badurl(self):
936122
+            """Just return 404 for each url with this prefix"""
936122
+            return self.return_not_found()
936122
+
936122
+        def serve_badgpg(self):
936122
+            """Instead of <path>/repomd.xml.asc returns content of <path>/repomd.xml.asc.bad"""
936122
+            path = self.parse_path('/yum/badgpg/')
936122
+            if path.endswith("repomd.xml.asc"):
936122
+                path += ".bad"
936122
+            self.serve_file(path)
936122
+
936122
+        def serve_auth_basic(self):
936122
+            """Page secured with basic HTTP auth; User: admin Password: secret"""
936122
+            if not self.check_auth():
936122
+                return self.authenticate()
936122
+            path = self.parse_path('/yum/auth_basic/')
936122
+            self.serve_file(path)
936122
+
936122
+        def serve_static(self):
936122
+            path = self.parse_path()
936122
+            self.serve_file(path)
936122
+
936122
+        def do_GET(self):
936122
+            if self.path.startswith('/yum/static/mirrorlist/'):
936122
+                return self.serve_mirrorlist_or_metalink_with_right_port()
936122
+            if self.path.startswith('/yum/static/metalink/'):
936122
+                return self.serve_mirrorlist_or_metalink_with_right_port()
936122
+            if self.path.startswith('/yum/harm_checksum/'):
936122
+                return self.serve_harm_checksum()
936122
+            if self.path.startswith('/yum/not_found/'):
936122
+                return self.serve_not_found()
936122
+            if self.path.startswith('/badurl/'):
936122
+                return self.serve_badurl()
936122
+            if self.path.startswith('/yum/badgpg/'):
936122
+                return self.serve_badgpg()
936122
+            if self.path.startswith('/yum/auth_basic/'):
936122
+                return self.serve_auth_basic()
936122
+            return self.serve_static()
936122
+
936122
+    return YumMockHandler
936122
 
936122
diff --git a/tests/python/tests/test_yum_package_downloading.py b/tests/python/tests/test_yum_package_downloading.py
936122
index 577a8ce..0364be0 100644
936122
--- a/tests/python/tests/test_yum_package_downloading.py
936122
+++ b/tests/python/tests/test_yum_package_downloading.py
936122
@@ -9,11 +9,10 @@ import xattr
936122
 
936122
 import tests.servermock.yum_mock.config as config
936122
 
936122
-from tests.base import TestCaseWithFlask
936122
-from tests.servermock.server import app
936122
+from tests.base import TestCaseWithServer
936122
 
936122
 
936122
-class TestCaseYumPackageDownloading(TestCaseWithFlask):
936122
+class TestCaseYumPackageDownloading(TestCaseWithServer):
936122
 
936122
     def setUp(self):
936122
         self.tmpdir = tempfile.mkdtemp(prefix="librepotest-", dir="./")
936122
@@ -163,9 +162,7 @@ class TestCaseYumPackageDownloading(TestCaseWithFlask):
936122
         pkg = os.path.join(self.tmpdir, config.PACKAGE_01_01)
936122
         self.assertTrue(os.path.isfile(pkg))
936122
 
936122
-class TestCaseYumPackagesDownloading(TestCaseWithFlask):
936122
-    application = app
936122
-
936122
+class TestCaseYumPackagesDownloading(TestCaseWithServer):
936122
 #    @classmethod
936122
 #    def setUpClass(cls):
936122
 #        super(TestCaseYumPackageDownloading, cls).setUpClass()
936122
diff --git a/tests/python/tests/test_yum_repo_downloading.py b/tests/python/tests/test_yum_repo_downloading.py
936122
index 76b067c..4d56d1c 100644
936122
--- a/tests/python/tests/test_yum_repo_downloading.py
936122
+++ b/tests/python/tests/test_yum_repo_downloading.py
936122
@@ -7,13 +7,12 @@ import unittest
936122
 
936122
 import librepo
936122
 
936122
-from tests.base import Context, TestCaseWithFlask, TEST_DATA
936122
-from tests.servermock.server import app
936122
+from tests.base import Context, TestCaseWithServer, TEST_DATA
936122
 import tests.servermock.yum_mock.config as config
936122
 
936122
 PUB_KEY = TEST_DATA+"/key.pub"
936122
 
936122
-class TestCaseYumRepoDownloading(TestCaseWithFlask):
936122
+class TestCaseYumRepoDownloading(TestCaseWithServer):
936122
 
936122
     def setUp(self):
936122
         self.tmpdir = tempfile.mkdtemp(prefix="librepotest-")
936122
--
936122
libgit2 1.0.1
936122