Test Failed
Branch chore/tox_py39_x (70f597)
by Vinicius
04:18
created

build.setup.Test.get_args()   A

Complexity

Conditions 4

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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