Compare commits

..
4 Commits
15 changed files with 282 additions and 253 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
-152
View File
@@ -1,152 +0,0 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
-58
View File
@@ -1,58 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="210d550b-e734-4e64-82ac-a059b804f492" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Python Script" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectColorInfo"><![CDATA[{
"associatedIndex": 8
}]]></component>
<component name="ProjectId" id="2cXmd8lpidvX3fV2PNgVtaX0lKv" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"git-widget-placeholder": "main"
}
}]]></component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-python-sdk-5a2391486177-d3b881c8e49f-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-233.13763.11" />
</set>
</attachedChunks>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="210d550b-e734-4e64-82ac-a059b804f492" name="Changes" comment="" />
<created>1708266383391</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1708266383391</updated>
</task>
<servers />
</component>
</project>
+11
View File
@@ -0,0 +1,11 @@
{
"python.testing.unittestArgs": [
"-v",
"-s",
"./tests",
"-p",
"*test.py"
],
"python.testing.pytestEnabled": false,
"python.testing.unittestEnabled": true
}
+15
View File
@@ -0,0 +1,15 @@
# Используем базовый образ Python
FROM python:3.9-slim
# Устанавливаем рабочую директорию
WORKDIR /app
# Копируем файлы проекта в контейнер
COPY src/ ./src
COPY requirements.txt ./
# Устанавливаем зависимости
RUN pip install --no-cache-dir -r requirements.txt
# Устанавливаем команду по умолчанию для запуска приложения
CMD ["python", "src/main.py"]
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2024 kromskii2
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+38 -2
View File
@@ -1,2 +1,38 @@
# Cleaners # my-project/README.md
Простая очистка пк
# My Project
## Overview
Этот проект предназначен для очистки временной папки, указанной в переменной окружения `TEMP`. Он включает в себя основную логику приложения, модульные тесты и автоматизацию развертывания.
## Установка
1. Клонируйте репозиторий:
```
git clone https://github.com/yourusername/my-project.git
```
2. Перейдите в директорию проекта:
```
cd my-project
```
3. Установите необходимые зависимости (если есть):
```
pip install -r requirements.txt
```
## Использование
Запустите основной скрипт для очистки временной папки:
```
python src/main.py
```
## Тестирование
Для запуска модульных тестов выполните:
```
pytest tests/test_main.py
```
## Развертывание
Скрипт развертывания находится в `scripts/deploy.sh`. Запустите его для автоматизации процесса развертывания.
## CI/CD
Проект использует GitHub Actions для автоматизации тестирования и развертывания. Конфигурация находится в `.github/workflows/ci.yml`.
+11
View File
@@ -0,0 +1,11 @@
version: '3.8'
services:
app:
build: .
container_name: my_project_app
environment:
- TEMP=/path/to/temp
volumes:
- .:/app
command: python src/main.py
+40
View File
@@ -0,0 +1,40 @@
# README.md
# My Project
## Обзор
Этот проект предназначен для очистки временной папки, указанной в переменной окружения `TEMP`. Он включает в себя основную логику приложения и модульные тесты для проверки функциональности.
## Установка
1. Клонируйте репозиторий:
```
git clone https://github.com/yourusername/my-project.git
```
2. Перейдите в каталог проекта:
```
cd my-project
```
3. Установите необходимые зависимости (если есть):
```
pip install -r requirements.txt
```
## Использование
Запустите основной скрипт для очистки временной папки:
```
python src/main.py
```
## Тестирование
Для запуска модульных тестов выполните:
```
pytest tests/test_main.py
```
## Развертывание
Скрипт развертывания находится в `scripts/deploy.sh`. Запустите его для автоматизации процесса развертывания.
-18
View File
@@ -1,18 +0,0 @@
import os
def clean_temp_folder():
temp_folder = os.environ.get('TEMP')
if temp_folder:
print(f"Cleaning Temp folder: {temp_folder}")
for root, dirs, files in os.walk(temp_folder):
for file in files:
try:
os.remove(os.path.join(root, file))
except Exception as e:
print(f"Error deleting {file}: {e}")
print("Temp folder has been cleaned.")
else:
print("Temp folder not found.")
if __name__ == "__main__":
clean_temp_folder()
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
# Скрипт для автоматизации процесса развертывания приложения
echo "Начало процесса развертывания..."
# Установка зависимостей
echo "Установка зависимостей..."
pip install -r requirements.txt
# Запуск приложения
echo "Запуск приложения..."
python src/main.py
echo "Процесс развертывания завершен."
+24
View File
@@ -0,0 +1,24 @@
import os
import logging
class TempFolderCleaner:
def __init__(self):
self.temp_folder = os.environ.get('TEMP')
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def clean_temp_folder(self):
if self.temp_folder:
logging.info(f"Очистка папки Temp: {self.temp_folder}")
for root, dirs, files in os.walk(self.temp_folder):
for file in files:
try:
os.remove(os.path.join(root, file))
except Exception as e:
logging.error(f"Ошибка при удалении {file}: {e}")
logging.info("Папка Temp очищена.")
else:
logging.warning("Папка Temp не найдена.")
if __name__ == "__main__":
cleaner = TempFolderCleaner()
cleaner.clean_temp_folder()
+60
View File
@@ -0,0 +1,60 @@
import os
import unittest
from unittest.mock import patch, MagicMock
from src.main import TempFolderCleaner
class TestCleanTempFolder(unittest.TestCase):
@patch('src.main.os.environ.get')
@patch('src.main.os.walk')
@patch('src.main.os.remove')
def test_clean_temp_folder(self, mock_remove, mock_walk, mock_get_env):
# Настройка тестовой среды
mock_get_env.return_value = '/mock/temp'
mock_walk.return_value = [
('/mock/temp', ('subdir',), ('file1.txt', 'file2.txt')),
('/mock/temp/subdir', (), ('file3.txt',))
]
cleaner = TempFolderCleaner()
cleaner.clean_temp_folder()
# Проверка, что os.remove был вызван для каждого файла
mock_remove.assert_any_call('/mock/temp/file1.txt')
mock_remove.assert_any_call('/mock/temp/file2.txt')
mock_remove.assert_any_call('/mock/temp/subdir/file3.txt')
self.assertEqual(mock_remove.call_count, 3)
@patch('src.main.os.environ.get')
@patch('src.main.os.walk')
@patch('src.main.os.remove')
def test_clean_temp_folder_with_errors(self, mock_remove, mock_walk, mock_get_env):
# Настройка тестовой среды
mock_get_env.return_value = '/mock/temp'
mock_walk.return_value = [
('/mock/temp', ('subdir',), ('file1.txt', 'file2.txt')),
('/mock/temp/subdir', (), ('file3.txt',))
]
mock_remove.side_effect = [None, Exception("Ошибка удаления"), None]
cleaner = TempFolderCleaner()
cleaner.clean_temp_folder()
# Проверка, что os.remove был вызван для каждого файла и обработка ошибок
mock_remove.assert_any_call('/mock/temp/file1.txt')
mock_remove.assert_any_call('/mock/temp/file2.txt')
mock_remove.assert_any_call('/mock/temp/subdir/file3.txt')
self.assertEqual(mock_remove.call_count, 3)
@patch('src.main.os.environ.get')
def test_temp_folder_not_found(self, mock_get_env):
# Настройка тестовой среды
mock_get_env.return_value = None
cleaner = TempFolderCleaner()
with self.assertLogs(level='WARNING') as log:
cleaner.clean_temp_folder()
self.assertIn('Папка Temp не найдена.', log.output[0])
if __name__ == '__main__':
unittest.main()
+25
View File
@@ -0,0 +1,25 @@
name: Lint Code Base
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.9'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8
- name: Run flake8
run: |
flake8 src/ tests/
+43
View File
@@ -0,0 +1,43 @@
name: CI
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: |
pytest tests/test_main.py
deploy:
runs-on: ubuntu-latest
needs: test
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Deploy application
run: |
bash scripts/deploy.sh