Example #1
0
def test_alt_domains_rules(tmp_path: Path, cloned_template: Path):
    """Asegurese de que las redirecciones de dominios alternativos sean buenas para Traefik."""
    copy(
        str(cloned_template),
        str(tmp_path),
        vcs_ref="HEAD",
        force=True,
        data={
            "domain_prod":
            "www.ejemplo.com",
            "domain_prod_alternatives": [
                "old.ejemplo.com",
                "ejemplo.com",
                "ejemplo.org",
                "www.ejemplo.org",
            ],
        },
    )
    with local.cwd(tmp_path):
        git("add", "prod.yaml")
        pre_commit("run", "-a", retcode=1)
    expected = Path("tests", "samples", "alt-domains", "prod.yaml").read_text()
    generated = (tmp_path / "prod.yaml").read_text()
    generated_scalar = yaml.load(generated)
    # Cualquiera de estos caracteres en una etiqueta traefik es un error casi seguro
    error_chars = ("\n", "'", '"')
    for service in generated_scalar["services"].values():
        for key, value in service.get("labels", {}).items():
            if not key.startswith("traefik."):
                continue
            for char in error_chars:
                assert char not in key
                assert char not in str(value)
    assert generated == expected
Example #2
0
def test_alt_domains_rules(tmp_path: Path, cloned_template: Path):
    """Make sure alt domains redirections are good for Traefik."""
    copy(
        str(cloned_template),
        str(tmp_path),
        vcs_ref="HEAD",
        force=True,
        data={
            "domain_prod":
            "www.example.com",
            "domain_prod_alternatives": [
                "old.example.com",
                "example.com",
                "example.org",
                "www.example.org",
            ],
        },
    )
    with local.cwd(tmp_path):
        git("add", "prod.yaml")
        pre_commit("run", "-a", retcode=1)
    expected = Path("tests", "samples", "alt-domains", "prod.yaml").read_text()
    generated = (tmp_path / "prod.yaml").read_text()
    generated_scalar = yaml.load(generated)
    # Any of these characters in a traefik label is an error almost for sure
    error_chars = ("\n", "'", '"')
    for service in generated_scalar["services"].values():
        for key, value in service.get("labels", {}).items():
            if not key.startswith("traefik."):
                continue
            for char in error_chars:
                assert char not in key
                assert char not in str(value)
    assert generated == expected
Example #3
0
def test_cidr_whitelist_rules(
    tmp_path: Path, cloned_template: Path, supported_odoo_version: float
):
    """Make sure CIDR whitelist redirections are good for Traefik."""
    copy(
        str(cloned_template),
        str(tmp_path),
        vcs_ref="HEAD",
        force=True,
        data={
            "odoo_version": supported_odoo_version,
            "project_name": "test-cidr-whitelist",
            "cidr_whitelist": ["123.123.123.123/24", "456.456.456.456"],
            "domains_prod": [{"hosts": ["www.example.com"]}],
            "domains_test": [{"hosts": ["demo.example.com"]}],
        },
    )
    # TODO Use Traefik to test this, instead of asserting labels
    key = ("test-cidr-whitelist-%.1f" % supported_odoo_version).replace(".", "-")
    with local.cwd(tmp_path):
        git("add", "prod.yaml", "test.yaml")
        pre_commit("run", "-a", retcode=None)
        prod = yaml.safe_load(docker_compose("-f", "prod.yaml", "config"))
        test = yaml.safe_load(docker_compose("-f", "test.yaml", "config"))
    # Assert prod.yaml
    assert (
        prod["services"]["odoo"]["labels"][
            f"traefik.http.middlewares.{key}-prod-whitelist.IPWhiteList.sourceRange"
        ]
        == "123.123.123.123/24, 456.456.456.456"
    )
    assert f"{key}-prod-whitelist" in prod["services"]["odoo"]["labels"][
        f"traefik.http.routers.{key}-prod-main-0.middlewares"
    ].split(", ")
    assert f"{key}-prod-whitelist" in prod["services"]["odoo"]["labels"][
        f"traefik.http.routers.{key}-prod-longpolling-0.middlewares"
    ].split(", ")
    assert f"{key}-prod-whitelist" in prod["services"]["odoo"]["labels"][
        f"traefik.http.routers.{key}-prod-forbiddenCrawlers-0.middlewares"
    ].split(", ")
    # Assert test.yaml
    assert (
        test["services"]["smtp"]["labels"][
            f"traefik.http.middlewares.{key}-test-whitelist.IPWhiteList.sourceRange"
        ]
        == "123.123.123.123/24, 456.456.456.456"
    )
    assert f"{key}-test-whitelist" in test["services"]["odoo"]["labels"][
        f"traefik.http.routers.{key}-test-forbiddenCrawlers-0.middlewares"
    ].split(", ")
    assert f"{key}-test-whitelist" in test["services"]["odoo"]["labels"][
        f"traefik.http.routers.{key}-test-longpolling-0.middlewares"
    ].split(", ")
    assert f"{key}-test-whitelist" in test["services"]["smtp"]["labels"][
        f"traefik.http.routers.{key}-test-mailhog-0.middlewares"
    ].split(", ")
def test_hooks_installable(tmp_path: Path, odoo_version: float,
                           cloned_template: Path):
    """Test that pre-commit hooks are installable."""
    data = {
        "odoo_version": odoo_version,
        "repo_slug": "website",
        "repo_name": "Test repo",
        "repo_description": "Test repo description",
    }
    copy(str(cloned_template), tmp_path, data=data, force=True)
    with local.cwd(tmp_path):
        git("init")
        pre_commit("install-hooks")
Example #5
0
def test_cidr_whitelist_rules(tmp_path: Path, cloned_template: Path):
    """Make sure CIDR whitelist redirections are good for Traefik."""
    copy(
        str(cloned_template),
        str(tmp_path),
        vcs_ref="HEAD",
        force=True,
        data={"cidr_whitelist": ["123.123.123.123/24", "456.456.456.456"]},
    )
    with local.cwd(tmp_path):
        git("add", "prod.yaml", "test.yaml")
        pre_commit("run", "-a", retcode=1)
    expected = Path("tests", "samples", "cidr-whitelist")
    assert (tmp_path / "prod.yaml").read_text() == (expected / "prod.yaml").read_text()
    assert (tmp_path / "test.yaml").read_text() == (expected / "test.yaml").read_text()
Example #6
0
def test_cidr_whitelist_rules(tmp_path: Path, cloned_template: Path):
    """Asegurese de que las redirecciones de la lista blanca CIDR sean buenas para Traefik."""
    copy(
        str(cloned_template),
        str(tmp_path),
        vcs_ref="HEAD",
        force=True,
        data={"cidr_whitelist": ["123.123.123.123/24", "456.456.456.456"]},
    )
    with local.cwd(tmp_path):
        git("add", "prod.yaml", "test.yaml")
        pre_commit("run", "-a", retcode=1)
    expected = Path("tests", "samples", "cidr-whitelist")
    assert (tmp_path / "prod.yaml").read_text() == (expected /
                                                    "prod.yaml").read_text()
    assert (tmp_path / "test.yaml").read_text() == (expected /
                                                    "test.yaml").read_text()
Example #7
0
def test_pre_commit_in_subproject(tmp_path: Path, cloned_template: Path,
                                  supported_odoo_version: float):
    """Test that .pre-commit-config.yaml has some specific settings fine."""
    copy(
        str(cloned_template),
        str(tmp_path),
        vcs_ref="HEAD",
        force=True,
        data={"odoo_version": supported_odoo_version},
    )
    # Make sure the template was correctly rendered
    pre_commit_config = yaml.safe_load(
        (tmp_path / ".pre-commit-config.yaml").read_text())
    is_py3 = supported_odoo_version >= 11
    found = 0
    should_find = 1
    for repo in pre_commit_config["repos"]:
        if repo["repo"] == "https://github.com/pre-commit/pre-commit-hooks":
            found += 1
            if is_py3:
                assert {"id": "debug-statements"} in repo["hooks"]
                assert {
                    "id": "fix-encoding-pragma",
                    "args": ["--remove"]
                } in repo["hooks"]
            else:
                assert {"id": "debug-statements"} not in repo["hooks"]
                assert {
                    "id": "fix-encoding-pragma",
                    "args": ["--remove"]
                } not in repo["hooks"]
                assert {"id": "fix-encoding-pragma"} in repo["hooks"]
    assert found == should_find
    # Make sure it reformats correctly some files
    with local.cwd(tmp_path / "odoo" / "custom" / "src" / "private"):
        git("add", "-A")
        git("commit", "-m", "hello world", retcode=1)
        git("commit", "-am", "hello world")
        manifest = "__manifest__" if is_py3 else "__openerp__"
        generate_test_addon("test_module", supported_odoo_version, ugly=True)
        git("add", "-A")
        git("commit", "-m", "added test_module", retcode=1)
        git("commit", "-am", "added test_module")
        expected_samples = {
            f"test_module/{manifest}.py":
            f"""\
                {"{"}
                    "name": "test_module",
                    "license": "AGPL-3",
                    "version": "{supported_odoo_version}.1.0.0",
                    "depends": ["base"],
                    "installable": True,
                    "auto_install": False,
                {"}"}
            """,
            "test_module/__init__.py":
            """\
                from . import models
            """,
            "test_module/models/__init__.py":
            """\
                from . import res_partner
            """,
            "test_module/models/res_partner.py":
            '''\
                import io
                import sys
                from logging import getLogger
                from os.path import join

                from requests import get

                import odoo
                from odoo import models

                _logger = getLogger(__name__)


                class ResPartner(models.Model):
                    _inherit = "res.partner"

                    def some_method(self, test):
                        """some weird
                        docstring"""
                        _logger.info(models, join, get, io, sys, odoo)
            ''',
        }
        for path, content in expected_samples.items():
            content = dedent(content)
            if not is_py3 and path.endswith(".py"):
                content = f"# -*- coding: utf-8 -*-\n{content}"
            assert Path(path).read_text() == content
    # Make sure it doesn't fail for incorrect module version when addon not installable
    with local.cwd(tmp_path / "odoo" / "custom" / "src" / "private"):
        # Bump version in test module and set as not installable
        generate_test_addon("test_module",
                            supported_odoo_version + 1,
                            installable=False)
        git("add", "-A")
        # First commit will add new module to the exclude list in pre-commit
        git("commit", "-m", "start migration of test_module", retcode=1)
        # Module should now be ignored by pre-commit and give no problems in commit
        git("commit", "-am", "start migration of test_module")
        # Load pre-commit config
        with open(tmp_path / ".pre-commit-config.yaml", "r") as fd:
            pre_commit_config = yaml.safe_load(fd.read())
        assert "^odoo/custom/src/private/test_module/|" in pre_commit_config[
            "exclude"]
        # Make sure uninstallable addon was ignored by pre-commit
        pre_commit("run", "-a")
        assert "test_module" not in git("status", "--porcelain")
    # It should still fail for installable addon with bad manifest
    with local.cwd(tmp_path / "odoo" / "custom" / "src" / "private"):
        # Mark test module as installable again
        generate_test_addon("test_module",
                            supported_odoo_version + 1,
                            installable=True)
        git("add", "-A")
        # First commit will remove test module to the exclude list in pre-commit
        git("commit", "-m", "Mark test module as installable again", retcode=1)
        # Commit should fail for incorrect version
        with pytest.raises(ProcessExecutionError):
            git("commit", "-am", "Mark test_module as installable again")
        # Load pre-commit config
        with open(tmp_path / ".pre-commit-config.yaml", "r") as fd:
            pre_commit_config = yaml.safe_load(fd.read())
        assert ("^odoo/custom/src/private/test_module/|"
                not in pre_commit_config["exclude"])