Unverified Commit 557700f7 authored by github-actions[bot]'s avatar github-actions[bot] Committed by GitHub
Browse files

Enhance test (#110)



* Enhance test

* Fix CSRF

---------

Co-authored-by: default avatarFedor Batonogov <f.batonogov@yandex.ru>
parent 98192d79
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -33,7 +33,7 @@ repos:
        args: [--autofix, --indent, '2', --offset, '2']

  - repo: https://github.com/asottile/pyupgrade
    rev: v3.17.0
    rev: v3.19.0
    hooks:
      - id: pyupgrade
        args: [--py312-plus]  # Указание минимальной версии Python для обновления синтаксиса
+9 −3
Original line number Diff line number Diff line
# Use ARG to set the Python version
ARG PYTHON_VERSION=3.13.0
FROM python:${PYTHON_VERSION}
SHELL ["/bin/bash", "-i", "-c"]

# Define maintainer information
LABEL maintainer="f.batonogov@yandex.ru"

# Define the PyInstaller version and necessary environment variables
ARG PYINSTALLER_VERSION=6.11.0

ENV PYPI_URL=https://pypi.python.org/
ENV PYPI_INDEX_URL=https://pypi.python.org/simple
ENV PYTHONUNBUFFERED=1

# Copy the entrypoint script
COPY entrypoint-linux.sh /entrypoint.sh

RUN pip3 install --no-cache-dir \
        pyinstaller==$PYINSTALLER_VERSION \
# Install dependencies, PyInstaller, and set execute permissions for the entrypoint
RUN pip install --no-cache-dir pyinstaller==$PYINSTALLER_VERSION \
    && chmod +x /entrypoint.sh

# Set the working directory and mount the volume
VOLUME /src/
WORKDIR /src/

# Set the entrypoint
ENTRYPOINT ["/entrypoint.sh"]
+16 −11
Original line number Diff line number Diff line
# Define Python version as an argument, using the slim variant for a smaller image
ARG PYTHON_VERSION=3.13.0-slim
FROM python:${PYTHON_VERSION}
SHELL ["/bin/bash", "-i", "-c"]

# Maintainer label for image metadata
LABEL maintainer="f.batonogov@yandex.ru"

# Define PyInstaller version as an argument
ARG PYINSTALLER_VERSION=6.11.0

# Configure Python Package Index URLs for pip
ENV PYPI_URL=https://pypi.python.org/
ENV PYPI_INDEX_URL=https://pypi.python.org/simple
ENV PYTHONUNBUFFERED=1

# Copy entrypoint script early to ensure it’s available before dependency installation
COPY entrypoint-linux.sh /entrypoint.sh

RUN apt update \
    && apt install -y \
# Install dependencies and PyInstaller in a single RUN command to reduce image layers
RUN apt update && \
    apt install --no-install-recommends -y \
        binutils \
        gcc \
        zlib1g-dev \
    && apt clean \
    && rm -rf \
        /var/lib/apt/lists/* \
        /var/cache/* \
    && pip3 install --no-cache-dir \
        pyinstaller==$PYINSTALLER_VERSION \
    && chmod +x /entrypoint.sh
        zlib1g-dev && \
    rm -rf /var/lib/apt/lists/* && \
    pip install --no-cache-dir pyinstaller==$PYINSTALLER_VERSION && \
    chmod +x /entrypoint.sh

VOLUME /src/
# Set the working directory and create a volume for source code
WORKDIR /src/
VOLUME /src/

# Use the entrypoint script as the container’s default entrypoint
ENTRYPOINT ["/entrypoint.sh"]
+13 −8
Original line number Diff line number Diff line
#!/bin/bash

if [ -z $1 ]; then
    echo "Enter dockerfile name"
if [ -z "$1" ]; then
    echo "Enter Dockerfile name"
    exit 1
fi

if ! command -v docker &>/dev/null && ! command -v podman &>/dev/null; then
    echo "Neither Docker nor Podman is installed"
    exit 1
fi

@@ -9,13 +14,13 @@ build_and_run() {
    local build_cmd=$1
    local run_cmd=$2
    local dockerfile=$3
    local pyinstaller_args=${4:-"--onefile"}

    $build_cmd -f $dockerfile -t pyinstaller_test . && \
    $run_cmd -v "$(pwd)/test:/src/" pyinstaller_test "pyinstaller main.py --onefile"
    $build_cmd -f "$dockerfile" -t pyinstaller_test . && \
    $run_cmd -v "$(pwd)/test:/src/" pyinstaller_test "pyinstaller main.py $pyinstaller_args"
}

# Try with Docker
if ! build_and_run "docker build" "docker run" $1; then
    # If Docker fails, try with Podman
    build_and_run "podman build" "podman run" $1
if ! build_and_run "docker build" "docker run" "$1"; then
    echo "Docker build failed, trying Podman..."
    build_and_run "podman build" "podman run" "$1"
fi
+71 −20
Original line number Diff line number Diff line
import logging
import random
import platform  # New import for OS information
import time
from datetime import datetime

import numpy as np
import pandas as pd
import requests
from flask import Flask, jsonify
from flask_wtf.csrf import CSRFProtect
from sqlalchemy import create_engine, text

# Logging configuration
logging.basicConfig(
    filename="app.log",
    filemode="a",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


# Function to log OS information
def log_os_info():
    os_info = platform.platform()
    logging.info(f"Operating System: {os_info}")


# Function to check requests functionality
def check_requests():
    max_retries = 3
    for attempt in range(1, max_retries + 1):
        try:
            response = requests.get("https://api.github.com")
        response.raise_for_status()  # Проверка на успешный статус
        print(f"Response Status Code: {response.status_code}")
            response.raise_for_status()
            logging.info(f"Request succeeded with status {response.status_code}")
            print(f"Response Content: {response.json()}")
            return
        except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
            logging.error(f"HTTP error on attempt {attempt}: {http_err}")
        except Exception as err:
        print(f"Other error occurred: {err}")
            logging.error(f"Other error on attempt {attempt}: {err}")
        time.sleep(2)
    print("All retries failed.")


# Function to test Pandas and NumPy functionality
def data_processing():
    data = np.random.rand(5, 3)
    df = pd.DataFrame(data, columns=["A", "B", "C"])
    logging.info(f"Generated DataFrame:\n{df}")
    print(df.describe())  # Data statistics


# Function to test Flask functionality
def start_flask_app():
    app = Flask(__name__)
    csrf = CSRFProtect()
    csrf.init_app(app)

    @app.route("/")
    def index():
        return jsonify(message="Hello from Flask!")

def log_request():
    logging.basicConfig(level=logging.INFO)
    logging.info(f"Request made at {datetime.now()}")
    app.run(port=5000)


def simulate_delay():
    delay = random.uniform(1, 3)
    print(f"Simulating delay of {delay:.2f} seconds")
    time.sleep(delay)
# Function to test SQLAlchemy functionality
def check_database():
    engine = create_engine("sqlite:///:memory:")
    with engine.connect() as connection:
        result = connection.execute(text("SELECT 'Hello, SQLAlchemy!'"))
        for row in result:
            logging.info(f"SQLAlchemy result: {row[0]}")
            print(f"SQLAlchemy result: {row[0]}")


# Main function
def main():
    log_request()
    simulate_delay()
    log_os_info()  # Log OS information
    logging.info("Starting main test process")
    check_requests()
    data_processing()
    check_database()
    # Run the Flask app in a separate thread if needed
    # from threading import Thread
    # flask_thread = Thread(target=start_flask_app)
    # flask_thread.start()


if __name__ == "__main__":
Loading