nano-dev-utils 0.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of nano-dev-utils might be problematic. Click here for more details.
- nano_dev_utils-0.2.1/.gitignore +177 -0
- nano_dev_utils-0.2.1/.idea/.gitignore +3 -0
- nano_dev_utils-0.2.1/.idea/inspectionProfiles/profiles_settings.xml +6 -0
- nano_dev_utils-0.2.1/.idea/misc.xml +7 -0
- nano_dev_utils-0.2.1/.idea/modules.xml +8 -0
- nano_dev_utils-0.2.1/.idea/nano_dev_utils.iml +8 -0
- nano_dev_utils-0.2.1/.idea/vcs.xml +6 -0
- nano_dev_utils-0.2.1/.idea/workspace.xml +69 -0
- nano_dev_utils-0.2.1/LICENSE.md +21 -0
- nano_dev_utils-0.2.1/PKG-INFO +137 -0
- nano_dev_utils-0.2.1/README.md +123 -0
- nano_dev_utils-0.2.1/pyproject.toml +23 -0
- nano_dev_utils-0.2.1/src/nano_dev_utils/__init__.py +14 -0
- nano_dev_utils-0.2.1/src/nano_dev_utils/dynamic_importer.py +28 -0
- nano_dev_utils-0.2.1/src/nano_dev_utils/release_ports.py +156 -0
- nano_dev_utils-0.2.1/src/nano_dev_utils/timers.py +24 -0
- nano_dev_utils-0.2.1/tests/__init__.py +12 -0
- nano_dev_utils-0.2.1/tests/testing_dynamic_importer.py +55 -0
- nano_dev_utils-0.2.1/tests/testing_release_ports.py +228 -0
- nano_dev_utils-0.2.1/tests/testing_timer.py +63 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py,cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
#Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
#uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
#poetry.lock
|
|
109
|
+
|
|
110
|
+
# pdm
|
|
111
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
112
|
+
#pdm.lock
|
|
113
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
114
|
+
# in version control.
|
|
115
|
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
116
|
+
.pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
121
|
+
__pypackages__/
|
|
122
|
+
|
|
123
|
+
# Celery stuff
|
|
124
|
+
celerybeat-schedule
|
|
125
|
+
celerybeat.pid
|
|
126
|
+
|
|
127
|
+
# SageMath parsed files
|
|
128
|
+
*.sage.py
|
|
129
|
+
|
|
130
|
+
# Environments
|
|
131
|
+
.env
|
|
132
|
+
.venv
|
|
133
|
+
env/
|
|
134
|
+
venv/
|
|
135
|
+
ENV/
|
|
136
|
+
env.bak/
|
|
137
|
+
venv.bak/
|
|
138
|
+
|
|
139
|
+
# Spyder project settings
|
|
140
|
+
.spyderproject
|
|
141
|
+
.spyproject
|
|
142
|
+
|
|
143
|
+
# Rope project settings
|
|
144
|
+
.ropeproject
|
|
145
|
+
|
|
146
|
+
# mkdocs documentation
|
|
147
|
+
/site
|
|
148
|
+
|
|
149
|
+
# mypy
|
|
150
|
+
.mypy_cache/
|
|
151
|
+
.dmypy.json
|
|
152
|
+
dmypy.json
|
|
153
|
+
|
|
154
|
+
# Pyre type checker
|
|
155
|
+
.pyre/
|
|
156
|
+
|
|
157
|
+
# pytype static type analyzer
|
|
158
|
+
.pytype/
|
|
159
|
+
|
|
160
|
+
# Cython debug symbols
|
|
161
|
+
cython_debug/
|
|
162
|
+
|
|
163
|
+
# PyCharm
|
|
164
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
165
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
166
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
167
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
168
|
+
#.idea/
|
|
169
|
+
|
|
170
|
+
# Ruff stuff:
|
|
171
|
+
.ruff_cache/
|
|
172
|
+
|
|
173
|
+
# PyPI configuration file
|
|
174
|
+
.pypirc
|
|
175
|
+
|
|
176
|
+
/src/*/debug.py
|
|
177
|
+
/src/*/*.log
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<project version="4">
|
|
3
|
+
<component name="Black">
|
|
4
|
+
<option name="sdkName" value="Python 3.10" />
|
|
5
|
+
</component>
|
|
6
|
+
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
|
|
7
|
+
</project>
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<project version="4">
|
|
3
|
+
<component name="ProjectModuleManager">
|
|
4
|
+
<modules>
|
|
5
|
+
<module fileurl="file://$PROJECT_DIR$/.idea/nano_dev_utils.iml" filepath="$PROJECT_DIR$/.idea/nano_dev_utils.iml" />
|
|
6
|
+
</modules>
|
|
7
|
+
</component>
|
|
8
|
+
</project>
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<module type="PYTHON_MODULE" version="4">
|
|
3
|
+
<component name="NewModuleRootManager">
|
|
4
|
+
<content url="file://$MODULE_DIR$" />
|
|
5
|
+
<orderEntry type="inheritedJdk" />
|
|
6
|
+
<orderEntry type="sourceFolder" forTests="false" />
|
|
7
|
+
</component>
|
|
8
|
+
</module>
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<project version="4">
|
|
3
|
+
<component name="ChangeListManager">
|
|
4
|
+
<list default="true" id="96bbbefe-efb6-42c4-93da-e069ac3e654f" name="Changes" comment="" />
|
|
5
|
+
<option name="SHOW_DIALOG" value="false" />
|
|
6
|
+
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
|
7
|
+
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
|
8
|
+
<option name="LAST_RESOLUTION" value="IGNORE" />
|
|
9
|
+
</component>
|
|
10
|
+
<component name="Git.Settings">
|
|
11
|
+
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
|
12
|
+
</component>
|
|
13
|
+
<component name="ProjectColorInfo">{
|
|
14
|
+
"associatedIndex": 5
|
|
15
|
+
}</component>
|
|
16
|
+
<component name="ProjectId" id="2wBUoAyjEyavXXmNnhB2xcAn4VQ" />
|
|
17
|
+
<component name="ProjectViewState">
|
|
18
|
+
<option name="hideEmptyMiddlePackages" value="true" />
|
|
19
|
+
<option name="showLibraryContents" value="true" />
|
|
20
|
+
<option name="showMembers" value="true" />
|
|
21
|
+
</component>
|
|
22
|
+
<component name="PropertiesComponent">{
|
|
23
|
+
"keyToString": {
|
|
24
|
+
"RunOnceActivity.ShowReadmeOnStart": "true",
|
|
25
|
+
"git-widget-placeholder": "master",
|
|
26
|
+
"last_opened_file_path": "C:/GitHubWS/nano_dev_utils"
|
|
27
|
+
}
|
|
28
|
+
}</component>
|
|
29
|
+
<component name="RunManager">
|
|
30
|
+
<configuration name="Python tests in tests" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
|
|
31
|
+
<module name="nano_dev_utils" />
|
|
32
|
+
<option name="ENV_FILES" value="" />
|
|
33
|
+
<option name="INTERPRETER_OPTIONS" value="" />
|
|
34
|
+
<option name="PARENT_ENVS" value="true" />
|
|
35
|
+
<option name="SDK_HOME" value="" />
|
|
36
|
+
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
|
|
37
|
+
<option name="IS_MODULE_SDK" value="true" />
|
|
38
|
+
<option name="ADD_CONTENT_ROOTS" value="true" />
|
|
39
|
+
<option name="ADD_SOURCE_ROOTS" value="true" />
|
|
40
|
+
<option name="_new_additionalArguments" value="""" />
|
|
41
|
+
<option name="_new_target" value=""$PROJECT_DIR$/tests"" />
|
|
42
|
+
<option name="_new_targetType" value=""PATH"" />
|
|
43
|
+
<method v="2" />
|
|
44
|
+
</configuration>
|
|
45
|
+
<recent_temporary>
|
|
46
|
+
<list>
|
|
47
|
+
<item itemvalue="Python tests.Python tests in tests" />
|
|
48
|
+
</list>
|
|
49
|
+
</recent_temporary>
|
|
50
|
+
</component>
|
|
51
|
+
<component name="SharedIndexes">
|
|
52
|
+
<attachedChunks>
|
|
53
|
+
<set>
|
|
54
|
+
<option value="bundled-python-sdk-5b207ade9991-746f403e7f0c-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-241.17890.14" />
|
|
55
|
+
</set>
|
|
56
|
+
</attachedChunks>
|
|
57
|
+
</component>
|
|
58
|
+
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
|
59
|
+
<component name="TaskManager">
|
|
60
|
+
<task active="true" id="Default" summary="Default task">
|
|
61
|
+
<changelist id="96bbbefe-efb6-42c4-93da-e069ac3e654f" name="Changes" comment="" />
|
|
62
|
+
<created>1745514632336</created>
|
|
63
|
+
<option name="number" value="Default" />
|
|
64
|
+
<option name="presentableId" value="Default" />
|
|
65
|
+
<updated>1745514632336</updated>
|
|
66
|
+
</task>
|
|
67
|
+
<servers />
|
|
68
|
+
</component>
|
|
69
|
+
</project>
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Yaron Dayan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nano_dev_utils
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: A collection of small Python utilities for developers.
|
|
5
|
+
Project-URL: Homepage, https://github.com/yaronday/nano_utils
|
|
6
|
+
Project-URL: Issues, https://github.com/yaronday/nano_utils/issues
|
|
7
|
+
Author-email: Yaron Dayan <yaronday77@gmail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE.md
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# nano_dev_utils
|
|
16
|
+
|
|
17
|
+
A collection of small Python utilities for developers.
|
|
18
|
+
|
|
19
|
+
## Modules
|
|
20
|
+
|
|
21
|
+
### `timers.py`
|
|
22
|
+
|
|
23
|
+
This module provides a `Timer` class for measuring the execution time of code blocks and functions.
|
|
24
|
+
|
|
25
|
+
#### `Timer` Class
|
|
26
|
+
|
|
27
|
+
* **`__init__(self, precision=4, verbose=False)`**: Initializes a `Timer` instance.
|
|
28
|
+
* `precision` (int, optional): The number of decimal places to record and
|
|
29
|
+
* display time durations. Defaults to 4.
|
|
30
|
+
* `verbose` (bool, optional): If `True`, the function's arguments and keyword
|
|
31
|
+
* arguments will be included in the printed timing output. Defaults to `False`.
|
|
32
|
+
* `timing_records` (list): A list to store the recorded timing durations as formatted strings.
|
|
33
|
+
|
|
34
|
+
* **`timeit(self, func)`**: A decorator that measures the execution time of the decorated function.
|
|
35
|
+
* When the decorated function is called, this decorator records the start and end times,
|
|
36
|
+
* calculates the total execution time, prints the function name and execution time
|
|
37
|
+
* (optionally including arguments if `verbose` is `True`), and returns the result of the original function.
|
|
38
|
+
|
|
39
|
+
#### Example Usage:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import time
|
|
43
|
+
from src.nano_dev_utils.timers import Timer
|
|
44
|
+
|
|
45
|
+
timer = Timer(precision=6, verbose=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@timer.timeit
|
|
49
|
+
def my_function(a, b=10):
|
|
50
|
+
"""A sample function."""
|
|
51
|
+
time.sleep(0.1)
|
|
52
|
+
return a + b
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
result = my_function(5, b=20)
|
|
56
|
+
print(f"Result: {result}")
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### `dynamic_importer.py`
|
|
60
|
+
|
|
61
|
+
This module provides an `Importer` class for lazy loading and caching module imports.
|
|
62
|
+
|
|
63
|
+
#### `Importer` Class
|
|
64
|
+
|
|
65
|
+
* **`__init__(self)`**: Initializes an `Importer` instance with an empty dictionary `imported_modules` to cache imported modules.
|
|
66
|
+
|
|
67
|
+
* **`import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any`**: Lazily imports a module from a specified library and caches it.
|
|
68
|
+
* `library` (str): The name of the library (e.g., "os", "requests").
|
|
69
|
+
* `module_name` (str): The name of the module to import within the library (e.g., "path", "get").
|
|
70
|
+
* Returns the imported module. If the module has already been imported, it returns the cached instance.
|
|
71
|
+
* Raises `ImportError` if the module cannot be found.
|
|
72
|
+
|
|
73
|
+
#### Example Usage:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from src.nano_dev_utils.dynamic_importer import Importer
|
|
77
|
+
|
|
78
|
+
importer = Importer()
|
|
79
|
+
|
|
80
|
+
os_path = importer.import_mod_from_lib("os", "path")
|
|
81
|
+
print(f"Imported os.path: {os_path}")
|
|
82
|
+
|
|
83
|
+
requests_get = importer.import_mod_from_lib("requests", "get")
|
|
84
|
+
print(f"Imported requests.get: {requests_get}")
|
|
85
|
+
|
|
86
|
+
# Subsequent calls will return the cached module
|
|
87
|
+
os_path_again = importer.import_mod_from_lib("os", "path")
|
|
88
|
+
print(f"Imported os.path again (cached): {os_path_again}")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### `release_ports.py`
|
|
92
|
+
|
|
93
|
+
This module provides a `PortsRelease` class to identify and release processes
|
|
94
|
+
listening on specified TCP ports. It supports Windows, Linux, and macOS.
|
|
95
|
+
|
|
96
|
+
#### `PortsRelease` Class
|
|
97
|
+
|
|
98
|
+
* **`__init__(self, default_ports: Optional[list[int]] = None)`**:
|
|
99
|
+
* Initializes a `PortsRelease` instance.
|
|
100
|
+
* `default_ports` (`list[int]`, *optional*): A list of default ports to manage.
|
|
101
|
+
* If not provided, it defaults to `[6277, 6274]`.
|
|
102
|
+
|
|
103
|
+
* **`get_pid_by_port(port: int) -> Optional[int]`**: A static method that attempts to
|
|
104
|
+
* find the process ID (PID) listening on the given `port`. It uses platform-specific
|
|
105
|
+
* commands (`netstat`, `ss`, `lsof`). Returns the PID if found, otherwise `None`.
|
|
106
|
+
|
|
107
|
+
* **`kill_process(pid: int) -> bool`**: A static method that attempts to kill the process
|
|
108
|
+
* with the given `pid`. It uses platform-specific commands (`taskkill`, `kill -9`).
|
|
109
|
+
* Returns `True` if the process was successfully killed, `False` otherwise.
|
|
110
|
+
|
|
111
|
+
* **`release_all(self, ports: Optional[list[int]] = None) -> None`**: Releases all processes
|
|
112
|
+
* listening on the specified `ports`.
|
|
113
|
+
* `ports` (`list[int]`, *optional*): A list of ports to release. If `None`, it uses the
|
|
114
|
+
* `default_ports` defined during initialization.
|
|
115
|
+
* For each port, it first tries to get the PID and then attempts to kill the process.
|
|
116
|
+
* It logs the actions and any errors encountered. Invalid port numbers in the provided list are skipped.
|
|
117
|
+
|
|
118
|
+
#### Example Usage:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from src.nano_dev_utils.release_ports import PortsRelease
|
|
122
|
+
|
|
123
|
+
# Create an instance with default ports
|
|
124
|
+
port_releaser = PortsRelease()
|
|
125
|
+
port_releaser.release_all()
|
|
126
|
+
|
|
127
|
+
# Create an instance with custom ports
|
|
128
|
+
custom_ports_releaser = PortsRelease(default_ports=[8080, 9000, 6274])
|
|
129
|
+
custom_ports_releaser.release_all(ports=[8080, 9000])
|
|
130
|
+
|
|
131
|
+
# Release only the default ports
|
|
132
|
+
port_releaser.release_all()
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
This project is licensed under the MIT License.
|
|
137
|
+
See [LICENSE](https://github.com/yaronday/nano_dev_utils/blob/master/README.md) for details.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# nano_dev_utils
|
|
2
|
+
|
|
3
|
+
A collection of small Python utilities for developers.
|
|
4
|
+
|
|
5
|
+
## Modules
|
|
6
|
+
|
|
7
|
+
### `timers.py`
|
|
8
|
+
|
|
9
|
+
This module provides a `Timer` class for measuring the execution time of code blocks and functions.
|
|
10
|
+
|
|
11
|
+
#### `Timer` Class
|
|
12
|
+
|
|
13
|
+
* **`__init__(self, precision=4, verbose=False)`**: Initializes a `Timer` instance.
|
|
14
|
+
* `precision` (int, optional): The number of decimal places to record and
|
|
15
|
+
* display time durations. Defaults to 4.
|
|
16
|
+
* `verbose` (bool, optional): If `True`, the function's arguments and keyword
|
|
17
|
+
* arguments will be included in the printed timing output. Defaults to `False`.
|
|
18
|
+
* `timing_records` (list): A list to store the recorded timing durations as formatted strings.
|
|
19
|
+
|
|
20
|
+
* **`timeit(self, func)`**: A decorator that measures the execution time of the decorated function.
|
|
21
|
+
* When the decorated function is called, this decorator records the start and end times,
|
|
22
|
+
* calculates the total execution time, prints the function name and execution time
|
|
23
|
+
* (optionally including arguments if `verbose` is `True`), and returns the result of the original function.
|
|
24
|
+
|
|
25
|
+
#### Example Usage:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import time
|
|
29
|
+
from src.nano_dev_utils.timers import Timer
|
|
30
|
+
|
|
31
|
+
timer = Timer(precision=6, verbose=True)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@timer.timeit
|
|
35
|
+
def my_function(a, b=10):
|
|
36
|
+
"""A sample function."""
|
|
37
|
+
time.sleep(0.1)
|
|
38
|
+
return a + b
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
result = my_function(5, b=20)
|
|
42
|
+
print(f"Result: {result}")
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### `dynamic_importer.py`
|
|
46
|
+
|
|
47
|
+
This module provides an `Importer` class for lazy loading and caching module imports.
|
|
48
|
+
|
|
49
|
+
#### `Importer` Class
|
|
50
|
+
|
|
51
|
+
* **`__init__(self)`**: Initializes an `Importer` instance with an empty dictionary `imported_modules` to cache imported modules.
|
|
52
|
+
|
|
53
|
+
* **`import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any`**: Lazily imports a module from a specified library and caches it.
|
|
54
|
+
* `library` (str): The name of the library (e.g., "os", "requests").
|
|
55
|
+
* `module_name` (str): The name of the module to import within the library (e.g., "path", "get").
|
|
56
|
+
* Returns the imported module. If the module has already been imported, it returns the cached instance.
|
|
57
|
+
* Raises `ImportError` if the module cannot be found.
|
|
58
|
+
|
|
59
|
+
#### Example Usage:
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from src.nano_dev_utils.dynamic_importer import Importer
|
|
63
|
+
|
|
64
|
+
importer = Importer()
|
|
65
|
+
|
|
66
|
+
os_path = importer.import_mod_from_lib("os", "path")
|
|
67
|
+
print(f"Imported os.path: {os_path}")
|
|
68
|
+
|
|
69
|
+
requests_get = importer.import_mod_from_lib("requests", "get")
|
|
70
|
+
print(f"Imported requests.get: {requests_get}")
|
|
71
|
+
|
|
72
|
+
# Subsequent calls will return the cached module
|
|
73
|
+
os_path_again = importer.import_mod_from_lib("os", "path")
|
|
74
|
+
print(f"Imported os.path again (cached): {os_path_again}")
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### `release_ports.py`
|
|
78
|
+
|
|
79
|
+
This module provides a `PortsRelease` class to identify and release processes
|
|
80
|
+
listening on specified TCP ports. It supports Windows, Linux, and macOS.
|
|
81
|
+
|
|
82
|
+
#### `PortsRelease` Class
|
|
83
|
+
|
|
84
|
+
* **`__init__(self, default_ports: Optional[list[int]] = None)`**:
|
|
85
|
+
* Initializes a `PortsRelease` instance.
|
|
86
|
+
* `default_ports` (`list[int]`, *optional*): A list of default ports to manage.
|
|
87
|
+
* If not provided, it defaults to `[6277, 6274]`.
|
|
88
|
+
|
|
89
|
+
* **`get_pid_by_port(port: int) -> Optional[int]`**: A static method that attempts to
|
|
90
|
+
* find the process ID (PID) listening on the given `port`. It uses platform-specific
|
|
91
|
+
* commands (`netstat`, `ss`, `lsof`). Returns the PID if found, otherwise `None`.
|
|
92
|
+
|
|
93
|
+
* **`kill_process(pid: int) -> bool`**: A static method that attempts to kill the process
|
|
94
|
+
* with the given `pid`. It uses platform-specific commands (`taskkill`, `kill -9`).
|
|
95
|
+
* Returns `True` if the process was successfully killed, `False` otherwise.
|
|
96
|
+
|
|
97
|
+
* **`release_all(self, ports: Optional[list[int]] = None) -> None`**: Releases all processes
|
|
98
|
+
* listening on the specified `ports`.
|
|
99
|
+
* `ports` (`list[int]`, *optional*): A list of ports to release. If `None`, it uses the
|
|
100
|
+
* `default_ports` defined during initialization.
|
|
101
|
+
* For each port, it first tries to get the PID and then attempts to kill the process.
|
|
102
|
+
* It logs the actions and any errors encountered. Invalid port numbers in the provided list are skipped.
|
|
103
|
+
|
|
104
|
+
#### Example Usage:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from src.nano_dev_utils.release_ports import PortsRelease
|
|
108
|
+
|
|
109
|
+
# Create an instance with default ports
|
|
110
|
+
port_releaser = PortsRelease()
|
|
111
|
+
port_releaser.release_all()
|
|
112
|
+
|
|
113
|
+
# Create an instance with custom ports
|
|
114
|
+
custom_ports_releaser = PortsRelease(default_ports=[8080, 9000, 6274])
|
|
115
|
+
custom_ports_releaser.release_all(ports=[8080, 9000])
|
|
116
|
+
|
|
117
|
+
# Release only the default ports
|
|
118
|
+
port_releaser.release_all()
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
This project is licensed under the MIT License.
|
|
123
|
+
See [LICENSE](https://github.com/yaronday/nano_dev_utils/blob/master/README.md) for details.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "nano_dev_utils"
|
|
3
|
+
version = "0.2.1"
|
|
4
|
+
authors = [
|
|
5
|
+
{ name="Yaron Dayan", email="yaronday77@gmail.com" },
|
|
6
|
+
]
|
|
7
|
+
description = "A collection of small Python utilities for developers."
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Operating System :: OS Independent",
|
|
13
|
+
]
|
|
14
|
+
license = "MIT"
|
|
15
|
+
license-files = ["LICENSE.md"]
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["hatchling >= 1.26"]
|
|
19
|
+
build-backend = "hatchling.build"
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/yaronday/nano_utils"
|
|
23
|
+
Issues = "https://github.com/yaronday/nano_utils/issues"
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Nano-Utils-Yaronday - A collection of small Python utilities for developers.
|
|
2
|
+
Copyright (c) 2025 Yaron Dayan
|
|
3
|
+
"""
|
|
4
|
+
from .dynamic_importer import Importer
|
|
5
|
+
from .timers import Timer
|
|
6
|
+
from .release_ports import PortsRelease, PROXY_SERVER, INSPECTOR_CLIENT
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Importer",
|
|
10
|
+
"Timer",
|
|
11
|
+
"PortsRelease",
|
|
12
|
+
"PROXY_SERVER",
|
|
13
|
+
"INSPECTOR_CLIENT",
|
|
14
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from types import ModuleType
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
import importlib
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Importer:
|
|
8
|
+
def __init__(self):
|
|
9
|
+
self.imported_modules = {}
|
|
10
|
+
|
|
11
|
+
def import_mod_from_lib(self, library: str, module_name: str) -> ModuleType | Any:
|
|
12
|
+
"""Lazily imports and caches a specific submodule from a given library.
|
|
13
|
+
:param library: The name of the library.
|
|
14
|
+
:param module_name: The name of the module to import.
|
|
15
|
+
:return: The imported module.
|
|
16
|
+
"""
|
|
17
|
+
if module_name in self.imported_modules:
|
|
18
|
+
return self.imported_modules[module_name]
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
module = importlib.import_module(f"{library}.{module_name}")
|
|
22
|
+
self.imported_modules[module_name] = module
|
|
23
|
+
return module
|
|
24
|
+
except ModuleNotFoundError as e:
|
|
25
|
+
raise ImportError(f"Could not import {library}.{module_name}") from e
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import platform
|
|
2
|
+
import subprocess
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
logging.basicConfig(filename='port release.log',
|
|
8
|
+
level=logging.INFO,
|
|
9
|
+
format='%(asctime)s - %(levelname)s: %(message)s',
|
|
10
|
+
datefmt='%d-%m-%Y %H:%M:%S')
|
|
11
|
+
lgr = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
PROXY_SERVER = 6277
|
|
14
|
+
INSPECTOR_CLIENT = 6274
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PortsRelease:
|
|
18
|
+
def __init__(self, default_ports: Optional[list[int]] = None):
|
|
19
|
+
self.default_ports: list[int] = default_ports \
|
|
20
|
+
if default_ports is not None else [PROXY_SERVER, INSPECTOR_CLIENT]
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def _log_process_found(port: int, pid: int) -> str:
|
|
24
|
+
return f'Process ID (PID) found for port {port}: {pid}.'
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def _log_process_terminated(pid: int, port: int) -> str:
|
|
28
|
+
return f'Process {pid} (on port {port}) terminated successfully.'
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def _log_no_process(port: int) -> str:
|
|
32
|
+
return f'No process found listening on port {port}.'
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
def _log_invalid_port(port: int) -> str:
|
|
36
|
+
return f'Invalid port number: {port}. Skipping.'
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def _log_terminate_failed(pid: int, port: Optional[int] = None,
|
|
40
|
+
error: Optional[str] = None) -> str:
|
|
41
|
+
base_msg = f'Failed to terminate process {pid}'
|
|
42
|
+
if port:
|
|
43
|
+
base_msg += f' (on port {port})'
|
|
44
|
+
if error:
|
|
45
|
+
base_msg += f'. Error: {error}'
|
|
46
|
+
return base_msg
|
|
47
|
+
|
|
48
|
+
@staticmethod
|
|
49
|
+
def _log_line_parse_failed(line: str) -> str:
|
|
50
|
+
return f'Could not parse PID from line: {line}'
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def _log_unexpected_error(e: Exception) -> str:
|
|
54
|
+
return f'An unexpected error occurred: {e}'
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def _log_cmd_error(error: bytes) -> str:
|
|
58
|
+
return f'Error running command: {error.decode()}'
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def _log_unsupported_os() -> str:
|
|
62
|
+
return f'Unsupported OS: {platform.system()}'
|
|
63
|
+
|
|
64
|
+
def get_pid_by_port(self, port: int) -> Optional[int]:
|
|
65
|
+
"""Gets the process ID (PID) listening on the specified port."""
|
|
66
|
+
try:
|
|
67
|
+
cmd: Optional[str] = {
|
|
68
|
+
"Windows": f"netstat -ano | findstr :{port}",
|
|
69
|
+
"Linux": f"ss -lntp | grep :{port}",
|
|
70
|
+
"Darwin": f"lsof -i :{port}",
|
|
71
|
+
}.get(platform.system())
|
|
72
|
+
if not cmd:
|
|
73
|
+
lgr.error(self._log_unsupported_os())
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
process = subprocess.Popen(cmd, shell=True,
|
|
77
|
+
stdout=subprocess.PIPE,
|
|
78
|
+
stderr=subprocess.PIPE)
|
|
79
|
+
output, error = process.communicate()
|
|
80
|
+
if error:
|
|
81
|
+
lgr.error(self._log_cmd_error(error))
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
lines: list[str] = output.decode().splitlines()
|
|
85
|
+
for line in lines:
|
|
86
|
+
if str(port) in line:
|
|
87
|
+
parts: list[str] = line.split()
|
|
88
|
+
if platform.system() == "Windows" and len(parts) > 4:
|
|
89
|
+
try:
|
|
90
|
+
return int(parts[4])
|
|
91
|
+
except ValueError:
|
|
92
|
+
lgr.error(self._log_line_parse_failed(line))
|
|
93
|
+
return None
|
|
94
|
+
elif platform.system() == "Linux":
|
|
95
|
+
for part in parts:
|
|
96
|
+
if "pid=" in part:
|
|
97
|
+
try:
|
|
98
|
+
return int(part.split("=")[1])
|
|
99
|
+
except ValueError:
|
|
100
|
+
lgr.error(self._log_line_parse_failed(line))
|
|
101
|
+
return None
|
|
102
|
+
elif platform.system() == "Darwin" and len(parts) > 1:
|
|
103
|
+
try:
|
|
104
|
+
return int(parts[1])
|
|
105
|
+
except ValueError:
|
|
106
|
+
lgr.error(self._log_line_parse_failed(line))
|
|
107
|
+
return None
|
|
108
|
+
return None
|
|
109
|
+
except Exception as e:
|
|
110
|
+
lgr.error(self._log_unexpected_error(e))
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
def kill_process(self, pid: int) -> bool:
|
|
114
|
+
"""Kills the process with the specified PID."""
|
|
115
|
+
try:
|
|
116
|
+
cmd: Optional[str] = {
|
|
117
|
+
'Windows': f'taskkill /F /PID {pid}',
|
|
118
|
+
'Linux': f'kill -9 {pid}',
|
|
119
|
+
'Darwin': f'kill -9 {pid}',
|
|
120
|
+
}.get(platform.system())
|
|
121
|
+
if not cmd:
|
|
122
|
+
lgr.error(self._log_unsupported_os())
|
|
123
|
+
return False
|
|
124
|
+
process = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
|
|
125
|
+
_, error = process.communicate()
|
|
126
|
+
if process.returncode:
|
|
127
|
+
error_msg = error.decode()
|
|
128
|
+
lgr.error(self._log_terminate_failed(pid=pid, error=error_msg))
|
|
129
|
+
return False
|
|
130
|
+
return True
|
|
131
|
+
except Exception as e:
|
|
132
|
+
lgr.error(self._log_unexpected_error(e))
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
def release_all(self, ports: Optional[list[int]] = None) -> None:
|
|
136
|
+
try:
|
|
137
|
+
ports_to_release: list[int] = self.default_ports if ports is None else ports
|
|
138
|
+
|
|
139
|
+
for port in ports_to_release:
|
|
140
|
+
if not isinstance(port, int):
|
|
141
|
+
lgr.error(self._log_invalid_port(port))
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
pid: Optional[int] = self.get_pid_by_port(port)
|
|
145
|
+
if pid is None:
|
|
146
|
+
lgr.info(self._log_no_process(port))
|
|
147
|
+
continue
|
|
148
|
+
|
|
149
|
+
lgr.info(self._log_process_found(port, pid))
|
|
150
|
+
if self.kill_process(pid):
|
|
151
|
+
lgr.info(self._log_process_terminated(pid, port))
|
|
152
|
+
else:
|
|
153
|
+
lgr.error(self._log_terminate_failed(pid=pid, port=port))
|
|
154
|
+
except Exception as e:
|
|
155
|
+
lgr.error(self._log_unexpected_error(e))
|
|
156
|
+
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from functools import wraps
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Timer:
|
|
6
|
+
def __init__(self, precision=4, verbose=False):
|
|
7
|
+
self.precision = precision
|
|
8
|
+
self.verbose = verbose
|
|
9
|
+
|
|
10
|
+
def timeit(self, func):
|
|
11
|
+
@wraps(func)
|
|
12
|
+
def timeit_wrapper(*args, **kwargs):
|
|
13
|
+
start_time = time.perf_counter()
|
|
14
|
+
result = func(*args, **kwargs)
|
|
15
|
+
end_time = time.perf_counter()
|
|
16
|
+
total_time = end_time - start_time
|
|
17
|
+
extra_info = f'{args} {kwargs} ' if self.verbose else ''
|
|
18
|
+
print(f'{func.__name__} {extra_info}took {total_time:.{self.precision}f} [s]')
|
|
19
|
+
return result
|
|
20
|
+
return timeit_wrapper
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .testing_timer import TestTimer
|
|
2
|
+
from .testing_dynamic_importer import TestImporter
|
|
3
|
+
from .testing_release_ports import (TestPortsRelease,
|
|
4
|
+
PROXY_SERVER, CLIENT_PORT)
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
TestTimer,
|
|
8
|
+
TestImporter,
|
|
9
|
+
TestPortsRelease,
|
|
10
|
+
PROXY_SERVER,
|
|
11
|
+
CLIENT_PORT,
|
|
12
|
+
]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from unittest.mock import patch
|
|
3
|
+
from types import ModuleType
|
|
4
|
+
from src.nano_dev_utils.dynamic_importer import Importer
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TestImporter(unittest.TestCase):
|
|
8
|
+
|
|
9
|
+
def setUp(self):
|
|
10
|
+
self.importer = Importer()
|
|
11
|
+
self.mock_module = ModuleType('mock_module')
|
|
12
|
+
self.mock_module.attribute = "test_value"
|
|
13
|
+
|
|
14
|
+
def test_import_mod_from_lib_success_new_import(self):
|
|
15
|
+
with patch("importlib.import_module",
|
|
16
|
+
return_value=self.mock_module) as mock_import:
|
|
17
|
+
module = self.importer.import_mod_from_lib("test_library",
|
|
18
|
+
"test_module")
|
|
19
|
+
self.assertEqual(module, self.mock_module)
|
|
20
|
+
self.assertIn("test_module", self.importer.imported_modules)
|
|
21
|
+
self.assertEqual(self.importer.imported_modules["test_module"], self.mock_module)
|
|
22
|
+
mock_import.assert_called_once_with("test_library.test_module")
|
|
23
|
+
|
|
24
|
+
def test_import_mod_from_lib_success_cached_import(self):
|
|
25
|
+
self.importer.imported_modules["cached_module"] = self.mock_module
|
|
26
|
+
with patch("importlib.import_module") as mock_import:
|
|
27
|
+
module = self.importer.import_mod_from_lib("another_library",
|
|
28
|
+
"cached_module")
|
|
29
|
+
self.assertEqual(module, self.mock_module)
|
|
30
|
+
mock_import.assert_not_called()
|
|
31
|
+
|
|
32
|
+
def test_import_mod_from_lib_failure(self):
|
|
33
|
+
with patch("importlib.import_module",
|
|
34
|
+
side_effect=ModuleNotFoundError("No module named "
|
|
35
|
+
"'nonexistent_library.missing_module'")):
|
|
36
|
+
with self.assertRaisesRegex(ImportError, "Could not import "
|
|
37
|
+
"nonexistent_library.missing_module"):
|
|
38
|
+
self.importer.import_mod_from_lib("nonexistent_library",
|
|
39
|
+
"missing_module")
|
|
40
|
+
self.assertNotIn("missing_module", self.importer.imported_modules)
|
|
41
|
+
|
|
42
|
+
def test_import_mod_from_lib_returns_any(self):
|
|
43
|
+
# Simulate importing a non-module object (though importlib.import_module typically returns modules)
|
|
44
|
+
mock_object = "not a module"
|
|
45
|
+
with patch.dict("sys.modules",
|
|
46
|
+
{"yet_another_library.some_object": mock_object}):
|
|
47
|
+
result = self.importer.import_mod_from_lib("yet_another_library",
|
|
48
|
+
"some_object")
|
|
49
|
+
self.assertEqual(result, mock_object)
|
|
50
|
+
self.assertIn("some_object", self.importer.imported_modules)
|
|
51
|
+
self.assertEqual(self.importer.imported_modules["some_object"], mock_object)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
if __name__ == '__main__':
|
|
55
|
+
unittest.main()
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from unittest.mock import patch, call
|
|
3
|
+
import logging
|
|
4
|
+
from src.nano_dev_utils import release_ports as rp
|
|
5
|
+
|
|
6
|
+
PROXY_SERVER = rp.PROXY_SERVER
|
|
7
|
+
CLIENT_PORT = rp.INSPECTOR_CLIENT
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestPortsRelease(unittest.TestCase):
|
|
11
|
+
|
|
12
|
+
def setUp(self):
|
|
13
|
+
self.ports_release = rp.PortsRelease()
|
|
14
|
+
self.mock_logger = unittest.mock.MagicMock(spec=logging.Logger)
|
|
15
|
+
|
|
16
|
+
self.remove_file_handlers()
|
|
17
|
+
|
|
18
|
+
patch.object(rp, 'lgr', self.mock_logger).start()
|
|
19
|
+
self.addCleanup(patch.stopall)
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def remove_file_handlers():
|
|
23
|
+
"""Temporarily remove any file handlers from the root logger"""
|
|
24
|
+
root_logger = logging.getLogger()
|
|
25
|
+
existing_file_handlers = [
|
|
26
|
+
handler for handler in root_logger.handlers
|
|
27
|
+
if isinstance(handler, logging.FileHandler)
|
|
28
|
+
]
|
|
29
|
+
for handler in existing_file_handlers:
|
|
30
|
+
root_logger.removeHandler(handler)
|
|
31
|
+
handler.close()
|
|
32
|
+
|
|
33
|
+
def tearDown(self):
|
|
34
|
+
patch.stopall()
|
|
35
|
+
|
|
36
|
+
def test_get_pid_by_port_linux_success(self):
|
|
37
|
+
with patch('platform.system', return_value='Linux'):
|
|
38
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
39
|
+
mock_process = unittest.mock.MagicMock()
|
|
40
|
+
mock_process.communicate.return_value = (b"tcp6 0 0 :::8080 "
|
|
41
|
+
b":::* users:((\"python3\",)"
|
|
42
|
+
b" pid=1234 fd=4)\n", b"")
|
|
43
|
+
mock_popen.return_value = mock_process
|
|
44
|
+
pid = self.ports_release.get_pid_by_port(8080)
|
|
45
|
+
self.assertEqual(pid, 1234)
|
|
46
|
+
mock_popen.assert_called_once_with('ss -lntp | grep :8080',
|
|
47
|
+
shell=True, stdout=unittest.mock.ANY,
|
|
48
|
+
stderr=unittest.mock.ANY)
|
|
49
|
+
|
|
50
|
+
def test_get_pid_by_port_windows_success(self):
|
|
51
|
+
with patch('platform.system', return_value='Windows'):
|
|
52
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
53
|
+
mock_process = unittest.mock.MagicMock()
|
|
54
|
+
mock_process.communicate.return_value = (b"TCP 0.0.0.0:"
|
|
55
|
+
b"9000 "
|
|
56
|
+
b"0.0.0.0:0"
|
|
57
|
+
b" "
|
|
58
|
+
b"LISTENING"
|
|
59
|
+
b" 5678\n", b"")
|
|
60
|
+
mock_popen.return_value = mock_process
|
|
61
|
+
pid = self.ports_release.get_pid_by_port(9000)
|
|
62
|
+
self.assertEqual(pid, 5678)
|
|
63
|
+
mock_popen.assert_called_once_with('netstat -ano | findstr :9000',
|
|
64
|
+
shell=True, stdout=unittest.mock.ANY,
|
|
65
|
+
stderr=unittest.mock.ANY)
|
|
66
|
+
|
|
67
|
+
def test_get_pid_by_port_darwin_success(self):
|
|
68
|
+
with patch('platform.system', return_value='Darwin'):
|
|
69
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
70
|
+
mock_process = unittest.mock.MagicMock()
|
|
71
|
+
mock_process.communicate.return_value = (b"python3 "
|
|
72
|
+
b"1111 user "
|
|
73
|
+
b"10u IPv4 "
|
|
74
|
+
b"0xabcdef0123456789"
|
|
75
|
+
b" 0t0 TCP *:"
|
|
76
|
+
b"7000 (LISTEN)\n", b"")
|
|
77
|
+
mock_popen.return_value = mock_process
|
|
78
|
+
pid = self.ports_release.get_pid_by_port(7000)
|
|
79
|
+
self.assertEqual(pid, 1111)
|
|
80
|
+
mock_popen.assert_called_once_with('lsof -i :7000',
|
|
81
|
+
shell=True, stdout=unittest.mock.ANY,
|
|
82
|
+
stderr=unittest.mock.ANY)
|
|
83
|
+
|
|
84
|
+
def test_get_pid_by_port_unsupported_os(self):
|
|
85
|
+
with patch('platform.system', return_value='UnsupportedOS'):
|
|
86
|
+
pid = self.ports_release.get_pid_by_port(1234)
|
|
87
|
+
self.assertIsNone(pid)
|
|
88
|
+
self.mock_logger.error.assert_called_once_with(self.ports_release.
|
|
89
|
+
_log_unsupported_os())
|
|
90
|
+
|
|
91
|
+
def test_get_pid_by_port_no_process(self):
|
|
92
|
+
with patch('platform.system', return_value='Linux'):
|
|
93
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
94
|
+
mock_process = unittest.mock.MagicMock()
|
|
95
|
+
mock_process.communicate.return_value = (b"", b"")
|
|
96
|
+
mock_popen.return_value = mock_process
|
|
97
|
+
pid = self.ports_release.get_pid_by_port(9999)
|
|
98
|
+
self.assertIsNone(pid)
|
|
99
|
+
|
|
100
|
+
def test_get_pid_by_port_command_error(self):
|
|
101
|
+
with patch('platform.system', return_value='Linux'):
|
|
102
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
103
|
+
mock_process = unittest.mock.MagicMock()
|
|
104
|
+
mock_process.communicate.return_value = (b"", b"Error occurred")
|
|
105
|
+
mock_popen.return_value = mock_process
|
|
106
|
+
pid = self.ports_release.get_pid_by_port(80)
|
|
107
|
+
self.assertIsNone(pid)
|
|
108
|
+
self.mock_logger.error.assert_called_once_with("Error running "
|
|
109
|
+
"command: Error occurred")
|
|
110
|
+
|
|
111
|
+
def test_get_pid_by_port_parse_error(self):
|
|
112
|
+
with patch('platform.system', return_value='Linux'):
|
|
113
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
114
|
+
mock_process = unittest.mock.MagicMock()
|
|
115
|
+
mock_process.communicate.return_value = (b"tcp6 0"
|
|
116
|
+
b" 0 "
|
|
117
|
+
b":::8080"
|
|
118
|
+
b" "
|
|
119
|
+
b":::* users:((\"python3\","
|
|
120
|
+
b"pid=invalid,fd=4))\n", b"")
|
|
121
|
+
mock_popen.return_value = mock_process
|
|
122
|
+
pid = self.ports_release.get_pid_by_port(8080)
|
|
123
|
+
self.assertIsNone(pid)
|
|
124
|
+
self.mock_logger.error.assert_called_once_with("Could not parse PID "
|
|
125
|
+
"from line: tcp6 0"
|
|
126
|
+
" 0 :::8080"
|
|
127
|
+
" :::*"
|
|
128
|
+
" users:((\"python3\","
|
|
129
|
+
"pid=invalid,fd=4))")
|
|
130
|
+
|
|
131
|
+
def test_get_pid_by_port_unexpected_exception(self):
|
|
132
|
+
with patch('platform.system', return_value='Linux'):
|
|
133
|
+
with patch('subprocess.Popen', side_effect=Exception("Unexpected")):
|
|
134
|
+
pid = self.ports_release.get_pid_by_port(1234)
|
|
135
|
+
self.assertIsNone(pid)
|
|
136
|
+
self.mock_logger.error.assert_called_once_with("An unexpected "
|
|
137
|
+
"error occurred: Unexpected")
|
|
138
|
+
|
|
139
|
+
def test_kill_process_success(self):
|
|
140
|
+
with patch('platform.system', return_value='Linux'):
|
|
141
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
142
|
+
mock_process = unittest.mock.MagicMock()
|
|
143
|
+
mock_process.returncode = 0
|
|
144
|
+
mock_process.communicate.return_value = (b"", b"")
|
|
145
|
+
mock_popen.return_value = mock_process
|
|
146
|
+
result = self.ports_release.kill_process(5678)
|
|
147
|
+
self.assertTrue(result)
|
|
148
|
+
mock_popen.assert_called_once_with('kill -9 5678',
|
|
149
|
+
shell=True, stderr=unittest.mock.ANY)
|
|
150
|
+
|
|
151
|
+
def test_kill_process_fail(self):
|
|
152
|
+
pid = 1234
|
|
153
|
+
err = 'Access denied'
|
|
154
|
+
with patch('platform.system', return_value='Windows'):
|
|
155
|
+
with patch('subprocess.Popen') as mock_popen:
|
|
156
|
+
mock_process = unittest.mock.MagicMock()
|
|
157
|
+
mock_process.returncode = 1
|
|
158
|
+
mock_process.communicate.return_value = (b"", err.encode('utf-8'))
|
|
159
|
+
mock_popen.return_value = mock_process
|
|
160
|
+
result = self.ports_release.kill_process(pid)
|
|
161
|
+
self.assertFalse(result)
|
|
162
|
+
self.mock_logger.error.assert_called_once_with(self.ports_release.
|
|
163
|
+
_log_terminate_failed(pid=pid, error="Access denied"))
|
|
164
|
+
|
|
165
|
+
def test_kill_process_unsupported_os(self):
|
|
166
|
+
with patch('platform.system', return_value='UnsupportedOS'):
|
|
167
|
+
result = self.ports_release.kill_process(9999)
|
|
168
|
+
self.assertFalse(result)
|
|
169
|
+
self.mock_logger.error.assert_called_once_with(self.ports_release.
|
|
170
|
+
_log_unsupported_os())
|
|
171
|
+
|
|
172
|
+
def test_kill_process_unexpected_exception(self):
|
|
173
|
+
err = Exception("Another error")
|
|
174
|
+
with (patch('platform.system', return_value='Linux')):
|
|
175
|
+
with patch('subprocess.Popen',
|
|
176
|
+
side_effect=err):
|
|
177
|
+
result = self.ports_release.kill_process(4321)
|
|
178
|
+
self.assertFalse(result)
|
|
179
|
+
self.mock_logger.error.assert_called_once_with(self.ports_release.
|
|
180
|
+
_log_unexpected_error(err))
|
|
181
|
+
|
|
182
|
+
@patch('testing_release_ports.rp.PortsRelease.get_pid_by_port')
|
|
183
|
+
@patch('testing_release_ports.rp.PortsRelease.kill_process')
|
|
184
|
+
def test_release_all_default_ports_success(self, mock_kill, mock_get_pid):
|
|
185
|
+
pid1, pid2 = 1111, 2222
|
|
186
|
+
mock_get_pid.side_effect = [pid1, pid2]
|
|
187
|
+
mock_kill.side_effect = [True, True]
|
|
188
|
+
self.ports_release.release_all()
|
|
189
|
+
mock_get_pid.assert_has_calls([call(PROXY_SERVER), call(CLIENT_PORT)])
|
|
190
|
+
mock_kill.assert_has_calls([call(pid1), call(pid2)])
|
|
191
|
+
self.assertEqual(mock_get_pid.call_count, 2)
|
|
192
|
+
self.assertEqual(mock_kill.call_count, 2)
|
|
193
|
+
self.mock_logger.info.assert_any_call(self.ports_release.
|
|
194
|
+
_log_process_found(PROXY_SERVER, pid1))
|
|
195
|
+
self.mock_logger.info.assert_any_call(self.ports_release.
|
|
196
|
+
_log_process_terminated(pid1, PROXY_SERVER))
|
|
197
|
+
self.mock_logger.info.assert_any_call(self.ports_release.
|
|
198
|
+
_log_process_found(CLIENT_PORT, pid2))
|
|
199
|
+
self.mock_logger.info.assert_any_call(self.ports_release.
|
|
200
|
+
_log_process_terminated(pid2, CLIENT_PORT))
|
|
201
|
+
|
|
202
|
+
def test_release_all_invalid_port(self):
|
|
203
|
+
with patch('testing_release_ports.rp.PortsRelease.get_pid_by_port') as mock_get_pid:
|
|
204
|
+
with patch('testing_release_ports.rp.PortsRelease.kill_process') as mock_kill:
|
|
205
|
+
# Make get_pid_by_port return None for the valid ports in this test
|
|
206
|
+
port = "invalid"
|
|
207
|
+
mock_get_pid.side_effect = [None, None]
|
|
208
|
+
self.ports_release.release_all(ports=[1234, "invalid", 5678])
|
|
209
|
+
mock_get_pid.assert_any_call(1234)
|
|
210
|
+
mock_get_pid.assert_any_call(5678)
|
|
211
|
+
self.assertEqual(mock_get_pid.call_count, 2)
|
|
212
|
+
mock_kill.assert_not_called()
|
|
213
|
+
self.mock_logger.error.assert_called_once_with(self.ports_release.
|
|
214
|
+
_log_invalid_port(port))
|
|
215
|
+
|
|
216
|
+
def test_release_all_unexpected_exception(self):
|
|
217
|
+
err = Exception("Release all error")
|
|
218
|
+
with patch('testing_release_ports.'
|
|
219
|
+
'rp.PortsRelease.get_pid_by_port',
|
|
220
|
+
side_effect=err):
|
|
221
|
+
self.ports_release.release_all(ports=[9010])
|
|
222
|
+
self.mock_logger.error.assert_called_once_with(self.ports_release.
|
|
223
|
+
_log_unexpected_error(err))
|
|
224
|
+
self.ports_release.get_pid_by_port.assert_called_once_with(9010)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
if __name__ == '__main__':
|
|
228
|
+
unittest.main()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from unittest.mock import patch
|
|
3
|
+
from src.nano_dev_utils.timers import Timer
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TestTimer(unittest.TestCase):
|
|
7
|
+
|
|
8
|
+
def test_initialization(self):
|
|
9
|
+
timer = Timer()
|
|
10
|
+
self.assertEqual(timer.precision, 4)
|
|
11
|
+
self.assertFalse(timer.verbose)
|
|
12
|
+
timer_custom = Timer(precision=6, verbose=True)
|
|
13
|
+
self.assertEqual(timer_custom.precision, 6)
|
|
14
|
+
self.assertTrue(timer_custom.verbose)
|
|
15
|
+
|
|
16
|
+
@patch('time.perf_counter')
|
|
17
|
+
@patch('builtins.print')
|
|
18
|
+
def test_timeit_simple(self, mock_print, mock_perf_counter):
|
|
19
|
+
mock_perf_counter.side_effect = [0, 0.12345]
|
|
20
|
+
timer = Timer(precision=5)
|
|
21
|
+
|
|
22
|
+
@timer.timeit
|
|
23
|
+
def sample_function():
|
|
24
|
+
return "result"
|
|
25
|
+
|
|
26
|
+
result = sample_function()
|
|
27
|
+
self.assertEqual(result, "result")
|
|
28
|
+
mock_perf_counter.assert_any_call()
|
|
29
|
+
mock_print.assert_called_once_with('sample_function took 0.12345 [s]')
|
|
30
|
+
|
|
31
|
+
@patch('time.perf_counter')
|
|
32
|
+
@patch('builtins.print')
|
|
33
|
+
def test_timeit_verbose(self, mock_print, mock_perf_counter):
|
|
34
|
+
mock_perf_counter.side_effect = [0, 0.56789]
|
|
35
|
+
timer = Timer(precision=3, verbose=True)
|
|
36
|
+
|
|
37
|
+
@timer.timeit
|
|
38
|
+
def another_function(arg1, kwarg1=None):
|
|
39
|
+
return "another result"
|
|
40
|
+
|
|
41
|
+
result = another_function(10, kwarg1="hello")
|
|
42
|
+
self.assertEqual(result, "another result")
|
|
43
|
+
mock_perf_counter.assert_any_call()
|
|
44
|
+
mock_print.assert_called_once_with("another_function (10,) {'kwarg1': 'hello'} took 0.568 [s]")
|
|
45
|
+
|
|
46
|
+
@patch('time.perf_counter')
|
|
47
|
+
@patch('builtins.print')
|
|
48
|
+
def test_timeit_no_args_kwargs(self, mock_print, mock_perf_counter):
|
|
49
|
+
mock_perf_counter.side_effect = [1.0, 1.5]
|
|
50
|
+
timer = Timer(precision=2, verbose=True)
|
|
51
|
+
|
|
52
|
+
@timer.timeit
|
|
53
|
+
def yet_another_function():
|
|
54
|
+
return "yet another result"
|
|
55
|
+
|
|
56
|
+
result = yet_another_function()
|
|
57
|
+
self.assertEqual(result, "yet another result")
|
|
58
|
+
mock_perf_counter.assert_any_call()
|
|
59
|
+
mock_print.assert_called_once_with("yet_another_function () {} took 0.50 [s]")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
if __name__ == '__main__':
|
|
63
|
+
unittest.main(argv=['first-arg-is-ignored'], exit=False)
|