# HG changeset patch
# User Georges Racinet <georges.racinet@octobus.net>
# Date 1576418222 -3600
#      Sun Dec 15 14:57:02 2019 +0100
# Branch heptapod-0-7
# Node ID 298421411299869c6a37936893b7978670271c63
# Parent  2e5babd588bed4f737c6382661809aae72f232d0
wsgi: actually using the given configuration file

This actually finishes ec9c7408d7dfda35163f588648a4917078f1885c,
in which I forgot to use the value. That was wrong, yet didn't break
anything in practice, because the hardcoded value is still the only
useful one outside of tests.

Doing the conditional instantiation in a class method allows to test it
independently without resorting to ugly stuff such as module
reload.

diff --git a/heptapod/tests/test_wsgi.py b/heptapod/tests/test_wsgi.py
--- a/heptapod/tests/test_wsgi.py
+++ b/heptapod/tests/test_wsgi.py
@@ -1,3 +1,4 @@
+import os
 import pytest
 from mercurial import (
     error,
@@ -43,6 +44,24 @@
     assert hgs.repos_root == str(tmpdir)
 
 
+def test_config_from_environ(tmpdir):
+    assert 'HEPTAPOD_HGRC' not in os.environ  # checking our premises
+    hgrc = tmpdir.join('hgrc')
+    repos = tmpdir.join('repositories')
+    hgrc.write('\n'.join(('[heptapod]\n',
+                          'repositories-root=' + str(repos),
+                          )))
+    try:
+        os.environ['HEPTAPOD_HGRC'] = str(hgrc)
+        hgs = HgServe.default_app()
+        assert hgs.repos_root == str(repos)
+    finally:
+        del os.environ['HEPTAPOD_HGRC']
+
+    # really make sure we won't pollute other tests
+    assert 'HEPTAPOD_HGRC' not in os.environ
+
+
 def test_apply_heptapod_headers(tmpdir):
     hgs = make_hgserve(tmpdir)
 
diff --git a/heptapod/wsgi.py b/heptapod/wsgi.py
--- a/heptapod/wsgi.py
+++ b/heptapod/wsgi.py
@@ -182,7 +182,11 @@
             res.setbodygen((e.message or b'') + b"\n")
             return res.sendresponse()
 
+    @classmethod
+    def default_app(cls):
+        HEPTAPOD_HGRC = os.environ.get('HEPTAPOD_HGRC')
+        if HEPTAPOD_HGRC:
+            return HgServe(conf_path=HEPTAPOD_HGRC)
 
-HEPTAPOD_HGRC = os.environ.get('HEPTAPOD_HGRC')
-if HEPTAPOD_HGRC:
-    hgserve = HgServe(conf_path="/etc/gitlab/heptapod.hgrc")
+
+hgserve = HgServe.default_app()