Test Failed
Pull Request — master (#19)
by Vinicius
06:20
created

build.setup.Test.get_args()   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 1
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
"""Setup script.
2
3
Run "python3 setup.py --help-commands" to list all available commands and their
4
descriptions.
5
"""
6
import os
7
import shutil
8
import sys
9
from abc import abstractmethod
10
from pathlib import Path
11
from subprocess import CalledProcessError, call, check_call
12
13
from setuptools import Command, setup
14
from setuptools.command.develop import develop
15
from setuptools.command.egg_info import egg_info
16
from setuptools.command.install import install
17
18
if 'bdist_wheel' in sys.argv:
19
    raise RuntimeError("This setup.py does not support wheels")
20
21
# Paths setup with virtualenv detection
22
BASE_ENV = Path(os.environ.get('VIRTUAL_ENV', '/'))
23
24
NAPP_NAME = 'sdntrace'
25
NAPP_USERNAME = 'amlight'
26
NAPP_VERSION = '2022.1.0'
27
28
# Kytos var folder
29
VAR_PATH = BASE_ENV / 'var' / 'lib' / 'kytos'
30
# Path for enabled NApps
31
ENABLED_PATH = VAR_PATH / 'napps'
32
# Path to install NApps
33
INSTALLED_PATH = VAR_PATH / 'napps' / '.installed'
34
CURRENT_DIR = Path('.').resolve()
35
36
# NApps enabled by default
37
ENABLED_NAPPS = [('amlight', 'coloring')]
38
39
40
class SimpleCommand(Command):
41
    """Make Command implementation simpler."""
42
43
    user_options = []
44
45
    @abstractmethod
46
    def run(self):
47
        """Run when command is invoked.
48
49
        Use *call* instead of *check_call* to ignore failures.
50
        """
51
52
    def initialize_options(self):
53
        """Set default values for options."""
54
55
    def finalize_options(self):
56
        """Post-process options."""
57
58
59
# pylint: disable=attribute-defined-outside-init, abstract-method
60
class TestCommand(Command):
61
    """Test tags decorators."""
62
63
    user_options = [
64
        ("k=", None, "Specify a pytest -k expression."),
65
    ]
66
67
    def get_args(self):
68
        """Return args to be used in test command."""
69
        if self.k:
70
            return f"-k '{self.k}'"
71
        return ""
72
73
    def initialize_options(self):
74
        """Set default size and type args."""
75
        self.k = ""
76
77
    def finalize_options(self):
78
        """Post-process."""
79
        pass
80
81
82
class Cleaner(SimpleCommand):
83
    """Custom clean command to tidy up the project root."""
84
85
    description = 'clean build, dist, pyc and egg from package and docs'
86
87
    def run(self):
88
        """Clean build, dist, pyc and egg from package and docs."""
89
        call('rm -vrf ./build ./dist ./*.egg-info', shell=True)
90
        call('find . -name __pycache__ -type d | xargs rm -rf', shell=True)
91
        call('make -C docs/ clean', shell=True)
92
93
94
class Test(TestCommand):
95
    """Run all tests."""
96
97
    description = "run tests and display results"
98
99
    def run(self):
100
        """Run tests."""
101
        cmd = f"python3 -m pytest tests/ {self.get_args()}"
102
        try:
103
            check_call(cmd, shell=True)
104
        except CalledProcessError as exc:
105
            print(exc)
106
            print('Unit tests failed. Fix the errors above and try again.')
107
            sys.exit(-1)
108
109
110
class TestCoverage(Test):
111
    """Display test coverage."""
112
113
    description = "run tests and display code coverage"
114
115
    def run(self):
116
        """Run tests quietly and display coverage report."""
117
        cmd = f"python3 -m pytest --cov=. tests/ {self.get_args()}"
118
        try:
119
            check_call(cmd, shell=True)
120
        except CalledProcessError as exc:
121
            print(exc)
122
            print('Coverage tests failed. Fix the errors above and try again.')
123
            sys.exit(-1)
124
125
126
class Linter(SimpleCommand):
127
    """Code linters."""
128
129
    description = 'lint Python source code'
130
131
    def run(self):
132
        """Run yala."""
133
        print('Yala is running. It may take several seconds...')
134
        try:
135
            cmd = "yala *.py tests"
136
            check_call(cmd, shell=True)
137
            print('No linter error found.')
138
        except CalledProcessError:
139
            print('Linter check failed. Fix the error(s) above and try again.')
140
            sys.exit(-1)
141
142
143
class KytosInstall:
144
    """Common code for all install types."""
145
146
    @staticmethod
147
    def enable_core_napps():
148
        """Enable a NAPP by creating a symlink."""
149
        (ENABLED_PATH / NAPP_USERNAME).mkdir(parents=True, exist_ok=True)
150
        for (user, napp) in ENABLED_NAPPS:
151
            napp_path = Path(user, napp)
152
            src = ENABLED_PATH / napp_path
153
            dst = INSTALLED_PATH / napp_path
154
            symlink_if_different(src, dst)
155
156
    def __str__(self):
157
        return self.__class__.__name__
158
159
160
class InstallMode(install):
161
    """Create files in var/lib/kytos."""
162
163
    description = 'To install NApps, use kytos-utils. Devs, see "develop".'
164
165
    def run(self):
166
        """Direct users to use kytos-utils to install NApps."""
167
        print(self.description)
168
169
170
class EggInfo(egg_info):
171
    """Prepare files to be packed."""
172
173
    def run(self):
174
        """Build css."""
175
        self._install_deps_wheels()
176
        super().run()
177
178
    @staticmethod
179
    def _install_deps_wheels():
180
        """Python wheels are much faster (no compiling)."""
181
        print("Installing dependencies...")
182
        check_call(
183
            [
184
                sys.executable,
185
                "-m",
186
                "pip",
187
                "install",
188
                "-r",
189
                "requirements/run.txt",
190
            ]
191
        )
192
193
194
class DevelopMode(develop):
195
    """Recommended setup for kytos-napps developers.
196
197
    Instead of copying the files to the expected directories, a symlink is
198
    created on the system aiming the current source code.
199
    """
200
201
    description = 'Install NApps in development mode'
202
203
    def run(self):
204
        """Install the package in a developer mode."""
205
        super().run()
206
        if self.uninstall:
207
            shutil.rmtree(str(ENABLED_PATH), ignore_errors=True)
208
        else:
209
            self._create_folder_symlinks()
210
            KytosInstall.enable_core_napps()
211
212
    @staticmethod
213
    def _create_folder_symlinks():
214
        """Symlink to all Kytos NApps folders.
215
216
        ./napps/kytos/napp_name will generate a link in
217
        var/lib/kytos/napps/.installed/kytos/napp_name.
218
        """
219
        links = INSTALLED_PATH / NAPP_USERNAME
220
        links.mkdir(parents=True, exist_ok=True)
221
        code = CURRENT_DIR
222
        src = links / NAPP_NAME
223
        symlink_if_different(src, code)
224
225
        (ENABLED_PATH / NAPP_USERNAME).mkdir(parents=True, exist_ok=True)
226
        dst = ENABLED_PATH / Path(NAPP_USERNAME, NAPP_NAME)
227
        symlink_if_different(dst, src)
228
229
    @staticmethod
230
    def _create_file_symlinks():
231
        """Symlink to required files."""
232
        src = ENABLED_PATH / '__init__.py'
233
        dst = CURRENT_DIR / '__init__.py'
234
        symlink_if_different(src, dst)
235
236
237
def read_requirements(path="requirements/run.txt"):
238
    """Read requirements file and return a list."""
239
    with open(path, "r", encoding="utf8") as file:
240
        return [
241
            line.strip()
242
            for line in file.readlines()
243
            if not line.startswith("#")
244
        ]
245
246
247
def symlink_if_different(path, target):
248
    """Force symlink creation if it points anywhere else."""
249
    # print(f"symlinking {path} to target: {target}...", end=" ")
250
    if not path.exists():
251
        # print(f"path doesn't exist. linking...")
252
        path.symlink_to(target)
253
    elif not path.samefile(target):
254
        # print(f"path exists, but is different. removing and linking...")
255
        # Exists but points to a different file, so let's replace it
256
        path.unlink()
257
        path.symlink_to(target)
258
259
260
setup(name=f'{NAPP_USERNAME}_{NAPP_NAME}',
261
      version=NAPP_VERSION,
262
      description='An OpenFlow Path Trace for the Kytos SDN controller',
263
      url='http://github.com/kytos-ng/sdntrace',
264
      author='Jeronimo Bezerra',
265
      author_email='[email protected]',
266
      license='MIT',
267
      install_requires=read_requirements() + ["setuptools >= 59.6.0"],
268
      packages=[],
269
      extras_require={
270
          'dev': [
271
              'pytest==7.0.0',
272
              'pytest-cov==3.0.0',
273
              "pip-tools",
274
              'yala',
275
              'tox',
276
          ],
277
      },
278
      cmdclass={
279
          'clean': Cleaner,
280
          'coverage': TestCoverage,
281
          'develop': DevelopMode,
282
          'install': InstallMode,
283
          'lint': Linter,
284
          'egg_info': EggInfo,
285
          'test': Test,
286
      },
287
      zip_safe=False,
288
      classifiers=[
289
          'License :: OSI Approved :: MIT License',
290
          'Operating System :: POSIX :: Linux',
291
          'Programming Language :: Python :: 3.9',
292
          'Topic :: System :: Networking',
293
      ])
294