Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #funcs.py
- # 2
- import numpy as np
- from flask import Blueprint, Flask, request, jsonify
- def sum_and_diff_lists(list1, list2):
- if len(list1) != len(list2):
- raise ValueError("Lists must be of the same length")
- sum_list = [a + b for a, b in zip(list1, list2)]
- diff_list = [a - b for a, b in zip(list1, list2)]
- return sum_list, diff_list
- def replace_below_average(lst):
- if not lst:
- return lst
- avg = sum(lst) / len(lst)
- return [x if x >= avg else 0 for x in lst]
- def last_negative_index(lst):
- for i in range(len(lst) - 1, -1, -1):
- if lst[i] < 0:
- return lst[i], i
- return None
- # 3
- def is_year_leap(year):
- if year % 4 == 0:
- if year % 100 == 0:
- if year % 400 == 0:
- return True
- else:
- return False
- else:
- return True
- else:
- return False
- def season(year):
- if year == 12 or year <= 2: return "Winter"
- if year <= 5: return "Spring"
- if year <= 8: return "Summer"
- if year <= 11: return "Autumn"
- return "Введите правильное значение месяца от 1 до 12"
- def is_prime(number):
- if number < 1 or number % 2 == 0 or number % 3 == 0: return False
- else:
- for i in range(5, int(number**0.5), 2):
- if number % i == 0:
- return False
- return True
- # 5
- def first_call(curs):
- curs.execute("select name from classroomfond ORDER BY name ASC")
- return curs.fetchall()
- # 6
- def first():
- arr1 = np.array([1,5,1,4,3,1,5,1,5,4,3,2])
- indices = np.where(arr1 == 5)[0]
- return indices
- def second():
- vector = np.arange(2, 12)
- return vector
- def third():
- arr3 = np.array([1, 9, 3, 12, 5, 8, 15, 7, 10])
- arr3[arr3 > 8] *= -1
- return arr3
- def sixth():
- matrix_border = np.zeros((6, 8), dtype=int)
- matrix_border[0, :] = 1
- matrix_border[-1, :] = 1
- matrix_border[:, 0] = 1
- matrix_border[:, -1] = 1
- return matrix_border
- # 10
- tasks = []
- next_id = 1
- def get_all_tasks():
- return tasks.copy()
- def get_task_by_id(task_id):
- for task in tasks:
- if task['id'] == task_id:
- return task
- return None
- def add_task(title, description=None, status="pending"):
- global next_id
- new_task = {
- 'id': next_id,
- 'title': title.strip(),
- 'description': description.strip() if description else None,
- 'status': status
- }
- tasks.append(new_task)
- next_id += 1
- return new_task
- def update_task(task_id, title=None, description=None, status=None):
- task = get_task_by_id(task_id)
- if not task:
- return None
- if title is not None:
- task['title'] = title.strip()
- if description is not None:
- task['description'] = description.strip() if description else None
- if status is not None:
- task['status'] = status
- return task
- def delete_task(task_id):
- global tasks
- task = get_task_by_id(task_id)
- if not task:
- return False
- tasks = [t for t in tasks if t['id'] != task_id]
- return True
- def get_tasks_by_status(status):
- return [task for task in tasks if task['status'] == status]
- def get_stats():
- done_count = len(get_tasks_by_status("done"))
- pending_count = len(get_tasks_by_status("pending"))
- return {
- "done": done_count,
- "pending": pending_count
- }
- api = Blueprint('api', __name__)
- @api.route('/tasks', methods=['GET'])
- def list_tasks():
- status_filter = request.args.get('status')
- if status_filter:
- tasks_list = get_tasks_by_status(status_filter)
- else:
- tasks_list = get_all_tasks()
- return jsonify(tasks_list)
- @api.route('/tasks', methods=['POST'])
- def create_task():
- data = request.get_json()
- if not data or 'title' not in data or not data['title'].strip():
- return jsonify({'error': 'Поле "title" обязательно и не может быть пустым'}), 400
- title = data['title']
- description = data.get('description')
- status = data.get('status', 'pending')
- if status not in ['pending', 'done']:
- return jsonify({'error': 'Некорректное значение статуса. Допустимые значения: "pending", "done"'}), 400
- new_task = add_task(title, description, status)
- return jsonify(new_task), 201
- @api.route('/tasks/<int:task_id>', methods=['GET'])
- def get_task(task_id):
- task = get_task_by_id(task_id)
- if not task:
- return jsonify({'error': 'Задача не найдена'}), 404
- return jsonify(task)
- @api.route('/tasks/<int:task_id>', methods=['PUT'])
- def update_task_route(task_id):
- data = request.get_json()
- if not data:
- return jsonify({'error': 'Тело запроса не может быть пустым'}), 400
- title = data.get('title')
- description = data.get('description')
- status = data.get('status')
- if status and status not in ['pending', 'done']:
- return jsonify({'error': 'Некорректное значение статуса. Допустимые значения: "pending", "done"'}), 400
- updated_task = update_task(task_id, title, description, status)
- if not updated_task:
- return jsonify({'error': 'Задача не найдена'}), 404
- return jsonify(updated_task)
- @api.route('/tasks/<int:task_id>', methods=['DELETE'])
- def delete_task_route(task_id):
- if not delete_task(task_id):
- return jsonify({'error': 'Задача не найдена'}), 404
- return jsonify({'message': 'Задача успешно удалена'}), 200
- @api.route('/tasks/stats', methods=['GET'])
- def stats():
- stats_data = get_stats()
- return jsonify(stats_data)
- def create_app():
- app = Flask(__name__)
- app.register_blueprint(api, url_prefix='/')
- return app
- #------------------------------------------------------------------------------------------
- tests.py
- import pymysql
- import pytest
- from funcs import *
- from unittest.mock import Mock
- # 2
- @pytest.fixture
- def lists_for_sum_diff():
- return {
- 'a': [1, 2, 3, 4],
- 'b': [0, -1, 2, -3],
- 'expected_sum': [1, 1, 5, 1],
- 'expected_diff': [1, 3, 1, 7]
- }
- @pytest.fixture
- def list_and_avg_for_replace():
- return {
- 'lst': [1, 2, 3, 4, 5],
- 'avg': 3.0,
- 'expected': [0, 0, 3, 4, 5]
- }
- @pytest.mark.pr2
- def test_sum_and_diff_lists(lists_for_sum_diff):
- a = lists_for_sum_diff['a']
- b = lists_for_sum_diff['b']
- expected = (lists_for_sum_diff['expected_sum'], lists_for_sum_diff['expected_diff'])
- result = sum_and_diff_lists(a, b)
- print(f"[PR2] sum_and_diff_lists({a}, {b}) → {result} (expected: {expected})")
- assert result == expected
- @pytest.mark.pr2
- def test_replace_below_average(list_and_avg_for_replace):
- lst = list_and_avg_for_replace['lst']
- expected = list_and_avg_for_replace['expected']
- result = replace_below_average(lst)
- print(f"[PR2] replace_below_average({lst}) → {result} (expected: {expected})")
- assert result == expected
- @pytest.mark.pr2
- def test_last_negative_index():
- lst = [1, -2, 3, -4, 5]
- expected = (-4, 3)
- result = last_negative_index(lst)
- print(f"[PR2] last_negative_index({lst}) → {result} (expected: {expected})")
- assert result == expected
- # 3
- @pytest.mark.pr3
- @pytest.mark.parametrize('x, expected', [
- (1992, True),
- (2000, True),
- (1900, False)
- ])
- def test_is_year_leap(x, expected):
- result = is_year_leap(x)
- print(f"[PR3] is_year_leap({x}) → {result} (expected: {expected})")
- assert result == expected
- @pytest.mark.pr3
- @pytest.mark.parametrize('x, expected', [
- (2, "Winter"),
- (6, "Summer"),
- (10, "Autumn")
- ])
- def test_season(x, expected):
- result = season(x)
- print(f"[PR3] season({x}) → '{result}' (expected: '{expected}')")
- assert result == expected
- @pytest.mark.pr3
- @pytest.mark.parametrize('x, expected', [
- (113, True),
- (114, False),
- (0, False)
- ])
- def test_is_prime(x, expected):
- result = is_prime(x)
- print(f"[PR3] is_prime({x}) → {result} (expected: {expected})")
- assert result == expected
- # 5
- @pytest.mark.pr5
- def test_mock_first_call():
- mock_cursor = Mock()
- mock_cursor.fetchall.return_value = (('А',), ('Б',), ('В',))
- result = first_call(mock_cursor)
- print(f"[PR5] mock call → result = {result}")
- mock_cursor.execute.assert_called_once_with("select name from classroomfond ORDER BY name ASC")
- assert result == (('А',), ('Б',), ('В',))
- @pytest.fixture
- def db_connection():
- con = pymysql.connect(host='localhost', user='root', password='', database='bd1')
- try:
- yield con
- finally:
- con.close()
- @pytest.mark.pr5
- def test_first_call_integration(db_connection):
- with db_connection.cursor() as cur:
- result = first_call(cur)
- print(f"[PR5] query result: {result}")
- assert result == (('А',), ('Б',), ('В',))
- # 7
- @pytest.mark.pr7
- def test_first():
- expected = [1, 6, 8]
- result = first().tolist()
- print(f"[PR7] first() → {result} (expected: {expected})")
- assert result == expected
- @pytest.mark.pr7
- def test_second():
- expected = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
- result = second().tolist()
- print(f"[PR7] second() → {result} (expected: {expected})")
- assert result == expected
- @pytest.mark.pr7
- def test_third():
- expected = [1, -9, 3, -12, 5, 8, -15, 7, -10]
- result = third().tolist()
- print(f"[PR7] third() → {result} (expected: {expected})")
- assert result == expected
- assert third().tolist() == expected
- @pytest.mark.pr7
- def test_sixth():
- expected = [[1, 1, 1, 1, 1, 1, 1, 1],
- [1, 0, 0, 0, 0, 0, 0, 1],
- [1, 0, 0, 0, 0, 0, 0, 1],
- [1, 0, 0, 0, 0, 0, 0, 1],
- [1, 0, 0, 0, 0, 0, 0, 1],
- [1, 1, 1, 1, 1, 1, 1, 1]]
- assert sixth().tolist() == expected
- # 10
- @pytest.fixture
- def client():
- app = create_app()
- app.config['TESTING'] = True
- with app.test_client() as client:
- tasks.clear()
- global next_id
- next_id = 1
- yield client
- @pytest.mark.pr10
- def test_create_task(client):
- resp = client.post('/tasks', json={
- 'title': 'Buy milk',
- 'description': 'Buy at least 1 liter',
- 'status': 'pending'
- })
- print(f"[PR10] Response: {resp.status_code}, body: {resp.get_json()}")
- assert resp.status_code == 201
- data = resp.get_json()
- assert data['title'] == 'Buy milk'
- assert data['id'] == 1
- assert len(tasks) == 1
- @pytest.mark.pr10
- def test_get_all_tasks(client):
- client.post('/tasks', json={'title': 'Task 1'})
- client.post('/tasks', json={'title': 'Task 2', 'status': 'done'})
- resp = client.get('/tasks')
- data = resp.get_json()
- print(f"[PR10] GET /tasks → {len(data)} tasks: {data}")
- assert resp.status_code == 200
- data = resp.get_json()
- assert len(data) == 2
- @pytest.mark.pr10
- def test_get_task_by_id(client):
- resp = client.post('/tasks', json={'title': 'Find me'})
- task_id = resp.get_json()['id']
- resp = client.get(f'/tasks/{task_id}')
- print(f"[PR10] GET /tasks/{task_id} → {resp.get_json()}")
- assert resp.status_code == 200
- assert resp.get_json()['title'] == 'Find me'
- @pytest.mark.pr10
- def test_get_nonexistent_task(client):
- resp = client.get('/tasks/999')
- print(f"[PR10] Response: {resp.status_code}, body: {resp.get_json()}")
- assert resp.status_code == 404
- assert 'error' in resp.get_json()
- @pytest.mark.pr10
- def test_update_task(client):
- resp = client.post('/tasks', json={'title': 'Old title', 'status': 'pending'})
- task_id = resp.get_json()['id']
- update_data = {'title': 'New title', 'status': 'done'}
- print(f"[PR10] PUT /tasks/{task_id} with {update_data}")
- resp = client.put(f'/tasks/{task_id}', json={
- 'title': 'New title',
- 'status': 'done'
- })
- assert resp.status_code == 200
- updated = resp.get_json()
- assert updated['title'] == 'New title'
- assert updated['status'] == 'done'
- @pytest.mark.pr10
- def test_delete_task(client):
- resp = client.post('/tasks', json={'title': 'To delete'})
- task_id = resp.get_json()['id']
- resp = client.delete(f'/tasks/{task_id}')
- print(f"[PR10] DELETE /tasks/{task_id}")
- assert resp.status_code == 200
- assert resp.get_json()['message'] == 'Задача успешно удалена'
- resp = client.get(f'/tasks/{task_id}')
- assert resp.status_code == 404
- #------------------------------------------------------------------------------------------
- pytest.ini
- [pytest]
- markers =
- pr2: Практическая работа №2
- pr3: Практическая работа №3
- pr5: Практическая работа №5
- pr7: Практическая работа №7
- pr10: Практическая работа №10
Advertisement
Add Comment
Please, Sign In to add comment