Teammasik

pythonDev/lr13

Dec 17th, 2025
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.08 KB | None | 0 0
  1. #funcs.py
  2. # 2
  3. import numpy as np
  4. from flask import Blueprint, Flask, request, jsonify
  5.  
  6. def sum_and_diff_lists(list1, list2):
  7.     if len(list1) != len(list2):
  8.         raise ValueError("Lists must be of the same length")
  9.     sum_list = [a + b for a, b in zip(list1, list2)]
  10.     diff_list = [a - b for a, b in zip(list1, list2)]
  11.     return sum_list, diff_list
  12.  
  13. def replace_below_average(lst):
  14.     if not lst:
  15.         return lst
  16.     avg = sum(lst) / len(lst)
  17.     return [x if x >= avg else 0 for x in lst]
  18.  
  19. def last_negative_index(lst):
  20.     for i in range(len(lst) - 1, -1, -1):
  21.         if lst[i] < 0:
  22.             return lst[i], i
  23.     return None
  24.  
  25.  
  26. # 3
  27. def is_year_leap(year):
  28.     if year % 4 == 0:
  29.         if year % 100 == 0:
  30.             if year % 400 == 0:
  31.                 return True
  32.             else:
  33.                 return False
  34.         else:
  35.             return True
  36.     else:
  37.         return False
  38.  
  39. def season(year):
  40.     if year == 12 or year <= 2: return "Winter"
  41.     if year <= 5: return "Spring"
  42.     if year <= 8: return "Summer"
  43.     if year <= 11: return "Autumn"
  44.     return "Введите правильное значение месяца от 1 до 12"
  45.  
  46. def is_prime(number):
  47.     if number < 1 or number % 2 == 0 or number % 3 == 0: return False
  48.     else:
  49.         for i in range(5, int(number**0.5), 2):
  50.             if number % i == 0:
  51.                 return False
  52.     return True
  53.  
  54.  
  55. # 5
  56. def first_call(curs):
  57.     curs.execute("select name from classroomfond ORDER BY name ASC")
  58.     return curs.fetchall()
  59.  
  60.  
  61. # 6
  62. def first():
  63.     arr1 = np.array([1,5,1,4,3,1,5,1,5,4,3,2])
  64.     indices = np.where(arr1 == 5)[0]
  65.     return indices
  66.  
  67. def second():
  68.     vector = np.arange(2, 12)
  69.     return vector
  70.  
  71. def third():
  72.     arr3 = np.array([1, 9, 3, 12, 5, 8, 15, 7, 10])
  73.     arr3[arr3 > 8] *= -1
  74.     return arr3
  75.  
  76. def sixth():
  77.     matrix_border = np.zeros((6, 8), dtype=int)
  78.  
  79.     matrix_border[0, :] = 1
  80.     matrix_border[-1, :] = 1
  81.     matrix_border[:, 0] = 1
  82.     matrix_border[:, -1] = 1
  83.  
  84.     return matrix_border
  85.  
  86.  
  87. # 10
  88. tasks = []
  89. next_id = 1
  90.  
  91. def get_all_tasks():
  92.     return tasks.copy()
  93.  
  94.  
  95. def get_task_by_id(task_id):
  96.     for task in tasks:
  97.         if task['id'] == task_id:
  98.             return task
  99.     return None
  100.  
  101.  
  102. def add_task(title, description=None, status="pending"):
  103.     global next_id
  104.     new_task = {
  105.         'id': next_id,
  106.         'title': title.strip(),
  107.         'description': description.strip() if description else None,
  108.         'status': status
  109.     }
  110.     tasks.append(new_task)
  111.     next_id += 1
  112.     return new_task
  113.  
  114.  
  115. def update_task(task_id, title=None, description=None, status=None):
  116.     task = get_task_by_id(task_id)
  117.     if not task:
  118.         return None
  119.  
  120.     if title is not None:
  121.         task['title'] = title.strip()
  122.     if description is not None:
  123.         task['description'] = description.strip() if description else None
  124.     if status is not None:
  125.         task['status'] = status
  126.     return task
  127.  
  128.  
  129. def delete_task(task_id):
  130.     global tasks
  131.     task = get_task_by_id(task_id)
  132.     if not task:
  133.         return False
  134.     tasks = [t for t in tasks if t['id'] != task_id]
  135.     return True
  136.  
  137.  
  138. def get_tasks_by_status(status):
  139.     return [task for task in tasks if task['status'] == status]
  140.  
  141.  
  142. def get_stats():
  143.     done_count = len(get_tasks_by_status("done"))
  144.     pending_count = len(get_tasks_by_status("pending"))
  145.     return {
  146.         "done": done_count,
  147.         "pending": pending_count
  148.     }
  149.  
  150.  
  151. api = Blueprint('api', __name__)
  152.  
  153. @api.route('/tasks', methods=['GET'])
  154. def list_tasks():
  155.     status_filter = request.args.get('status')
  156.     if status_filter:
  157.         tasks_list = get_tasks_by_status(status_filter)
  158.     else:
  159.         tasks_list = get_all_tasks()
  160.     return jsonify(tasks_list)
  161.  
  162.  
  163. @api.route('/tasks', methods=['POST'])
  164. def create_task():
  165.     data = request.get_json()
  166.     if not data or 'title' not in data or not data['title'].strip():
  167.         return jsonify({'error': 'Поле "title" обязательно и не может быть пустым'}), 400
  168.  
  169.     title = data['title']
  170.     description = data.get('description')
  171.     status = data.get('status', 'pending')
  172.  
  173.     if status not in ['pending', 'done']:
  174.         return jsonify({'error': 'Некорректное значение статуса. Допустимые значения: "pending", "done"'}), 400
  175.  
  176.     new_task = add_task(title, description, status)
  177.     return jsonify(new_task), 201
  178.  
  179.  
  180. @api.route('/tasks/<int:task_id>', methods=['GET'])
  181. def get_task(task_id):
  182.     task = get_task_by_id(task_id)
  183.     if not task:
  184.         return jsonify({'error': 'Задача не найдена'}), 404
  185.     return jsonify(task)
  186.  
  187.  
  188. @api.route('/tasks/<int:task_id>', methods=['PUT'])
  189. def update_task_route(task_id):
  190.     data = request.get_json()
  191.     if not data:
  192.         return jsonify({'error': 'Тело запроса не может быть пустым'}), 400
  193.  
  194.     title = data.get('title')
  195.     description = data.get('description')
  196.     status = data.get('status')
  197.  
  198.     if status and status not in ['pending', 'done']:
  199.         return jsonify({'error': 'Некорректное значение статуса. Допустимые значения: "pending", "done"'}), 400
  200.  
  201.     updated_task = update_task(task_id, title, description, status)
  202.     if not updated_task:
  203.         return jsonify({'error': 'Задача не найдена'}), 404
  204.  
  205.     return jsonify(updated_task)
  206.  
  207.  
  208. @api.route('/tasks/<int:task_id>', methods=['DELETE'])
  209. def delete_task_route(task_id):
  210.     if not delete_task(task_id):
  211.         return jsonify({'error': 'Задача не найдена'}), 404
  212.     return jsonify({'message': 'Задача успешно удалена'}), 200
  213.  
  214.  
  215. @api.route('/tasks/stats', methods=['GET'])
  216. def stats():
  217.     stats_data = get_stats()
  218.     return jsonify(stats_data)
  219.  
  220. def create_app():
  221.     app = Flask(__name__)
  222.     app.register_blueprint(api, url_prefix='/')
  223.     return app
  224.  
  225.  
  226. #------------------------------------------------------------------------------------------
  227.  
  228. tests.py
  229. import pymysql
  230. import pytest
  231. from funcs import *
  232. from unittest.mock import Mock
  233.  
  234. # 2
  235. @pytest.fixture
  236. def lists_for_sum_diff():
  237.     return {
  238.         'a': [1, 2, 3, 4],
  239.         'b': [0, -1, 2, -3],
  240.         'expected_sum': [1, 1, 5, 1],
  241.         'expected_diff': [1, 3, 1, 7]
  242.     }
  243.  
  244.  
  245. @pytest.fixture
  246. def list_and_avg_for_replace():
  247.     return {
  248.         'lst': [1, 2, 3, 4, 5],
  249.         'avg': 3.0,
  250.         'expected': [0, 0, 3, 4, 5]
  251.     }
  252.  
  253. @pytest.mark.pr2
  254. def test_sum_and_diff_lists(lists_for_sum_diff):
  255.     a = lists_for_sum_diff['a']
  256.     b = lists_for_sum_diff['b']
  257.     expected = (lists_for_sum_diff['expected_sum'], lists_for_sum_diff['expected_diff'])
  258.     result = sum_and_diff_lists(a, b)
  259.     print(f"[PR2] sum_and_diff_lists({a}, {b}) → {result} (expected: {expected})")
  260.     assert result == expected
  261.  
  262. @pytest.mark.pr2
  263. def test_replace_below_average(list_and_avg_for_replace):
  264.     lst = list_and_avg_for_replace['lst']
  265.     expected = list_and_avg_for_replace['expected']
  266.     result = replace_below_average(lst)
  267.     print(f"[PR2] replace_below_average({lst}) → {result} (expected: {expected})")
  268.     assert result == expected
  269.  
  270. @pytest.mark.pr2
  271. def test_last_negative_index():
  272.     lst = [1, -2, 3, -4, 5]
  273.     expected = (-4, 3)
  274.     result = last_negative_index(lst)
  275.     print(f"[PR2] last_negative_index({lst}) → {result} (expected: {expected})")
  276.     assert result == expected
  277.  
  278.  
  279. # 3
  280. @pytest.mark.pr3
  281. @pytest.mark.parametrize('x, expected', [
  282.     (1992, True),
  283.     (2000, True),
  284.     (1900, False)
  285. ])
  286. def test_is_year_leap(x, expected):
  287.     result = is_year_leap(x)
  288.     print(f"[PR3] is_year_leap({x}) → {result} (expected: {expected})")
  289.     assert result == expected
  290.  
  291. @pytest.mark.pr3
  292. @pytest.mark.parametrize('x, expected', [
  293.     (2, "Winter"),
  294.     (6, "Summer"),
  295.     (10, "Autumn")
  296. ])
  297. def test_season(x, expected):
  298.     result = season(x)
  299.     print(f"[PR3] season({x}) → '{result}' (expected: '{expected}')")
  300.     assert result == expected
  301.  
  302. @pytest.mark.pr3
  303. @pytest.mark.parametrize('x, expected', [
  304.     (113, True),
  305.     (114, False),
  306.     (0, False)
  307. ])
  308. def test_is_prime(x, expected):
  309.     result = is_prime(x)
  310.     print(f"[PR3] is_prime({x}) → {result} (expected: {expected})")
  311.     assert result == expected
  312.  
  313.  
  314. # 5
  315. @pytest.mark.pr5
  316. def test_mock_first_call():
  317.     mock_cursor = Mock()
  318.     mock_cursor.fetchall.return_value = (('А',), ('Б',), ('В',))
  319.     result = first_call(mock_cursor)
  320.     print(f"[PR5] mock call → result = {result}")
  321.     mock_cursor.execute.assert_called_once_with("select name from classroomfond ORDER BY name ASC")
  322.     assert result == (('А',), ('Б',), ('В',))
  323.  
  324.  
  325. @pytest.fixture
  326. def db_connection():
  327.     con = pymysql.connect(host='localhost', user='root', password='', database='bd1')
  328.     try:
  329.         yield con
  330.     finally:
  331.         con.close()
  332.  
  333. @pytest.mark.pr5
  334. def test_first_call_integration(db_connection):
  335.     with db_connection.cursor() as cur:
  336.         result = first_call(cur)
  337.         print(f"[PR5] query result: {result}")
  338.         assert result == (('А',), ('Б',), ('В',))
  339.  
  340. # 7
  341. @pytest.mark.pr7
  342. def test_first():
  343.     expected = [1, 6, 8]
  344.     result = first().tolist()
  345.     print(f"[PR7] first() → {result} (expected: {expected})")
  346.     assert result == expected
  347.  
  348. @pytest.mark.pr7
  349. def test_second():
  350.     expected = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  351.     result = second().tolist()
  352.     print(f"[PR7] second() → {result} (expected: {expected})")
  353.     assert result == expected
  354.  
  355. @pytest.mark.pr7
  356. def test_third():
  357.     expected = [1, -9, 3, -12, 5, 8, -15, 7, -10]
  358.     result = third().tolist()
  359.     print(f"[PR7] third() → {result} (expected: {expected})")
  360.     assert result == expected
  361.     assert third().tolist() == expected
  362.  
  363. @pytest.mark.pr7
  364. def test_sixth():
  365.     expected = [[1, 1, 1, 1, 1, 1, 1, 1],
  366.         [1, 0, 0, 0, 0, 0, 0, 1],
  367.         [1, 0, 0, 0, 0, 0, 0, 1],
  368.         [1, 0, 0, 0, 0, 0, 0, 1],
  369.         [1, 0, 0, 0, 0, 0, 0, 1],
  370.         [1, 1, 1, 1, 1, 1, 1, 1]]
  371.     assert sixth().tolist() == expected
  372.  
  373.  
  374. # 10
  375. @pytest.fixture
  376. def client():
  377.     app = create_app()
  378.     app.config['TESTING'] = True
  379.     with app.test_client() as client:
  380.         tasks.clear()
  381.         global next_id
  382.         next_id = 1
  383.         yield client
  384.  
  385.  
  386. @pytest.mark.pr10
  387. def test_create_task(client):
  388.     resp = client.post('/tasks', json={
  389.         'title': 'Buy milk',
  390.         'description': 'Buy at least 1 liter',
  391.         'status': 'pending'
  392.     })
  393.     print(f"[PR10] Response: {resp.status_code}, body: {resp.get_json()}")
  394.     assert resp.status_code == 201
  395.     data = resp.get_json()
  396.     assert data['title'] == 'Buy milk'
  397.     assert data['id'] == 1
  398.     assert len(tasks) == 1
  399.  
  400.  
  401. @pytest.mark.pr10
  402. def test_get_all_tasks(client):
  403.     client.post('/tasks', json={'title': 'Task 1'})
  404.     client.post('/tasks', json={'title': 'Task 2', 'status': 'done'})
  405.     resp = client.get('/tasks')
  406.     data = resp.get_json()
  407.     print(f"[PR10] GET /tasks → {len(data)} tasks: {data}")
  408.     assert resp.status_code == 200
  409.     data = resp.get_json()
  410.     assert len(data) == 2
  411.  
  412.  
  413. @pytest.mark.pr10
  414. def test_get_task_by_id(client):
  415.     resp = client.post('/tasks', json={'title': 'Find me'})
  416.     task_id = resp.get_json()['id']
  417.     resp = client.get(f'/tasks/{task_id}')
  418.     print(f"[PR10] GET /tasks/{task_id} → {resp.get_json()}")
  419.     assert resp.status_code == 200
  420.     assert resp.get_json()['title'] == 'Find me'
  421.  
  422.  
  423. @pytest.mark.pr10
  424. def test_get_nonexistent_task(client):
  425.     resp = client.get('/tasks/999')
  426.     print(f"[PR10] Response: {resp.status_code}, body: {resp.get_json()}")
  427.     assert resp.status_code == 404
  428.     assert 'error' in resp.get_json()
  429.  
  430.  
  431. @pytest.mark.pr10
  432. def test_update_task(client):
  433.     resp = client.post('/tasks', json={'title': 'Old title', 'status': 'pending'})
  434.     task_id = resp.get_json()['id']
  435.     update_data = {'title': 'New title', 'status': 'done'}
  436.     print(f"[PR10] PUT /tasks/{task_id} with {update_data}")
  437.     resp = client.put(f'/tasks/{task_id}', json={
  438.         'title': 'New title',
  439.         'status': 'done'
  440.     })
  441.     assert resp.status_code == 200
  442.     updated = resp.get_json()
  443.     assert updated['title'] == 'New title'
  444.     assert updated['status'] == 'done'
  445.  
  446.  
  447. @pytest.mark.pr10
  448. def test_delete_task(client):
  449.     resp = client.post('/tasks', json={'title': 'To delete'})
  450.     task_id = resp.get_json()['id']
  451.     resp = client.delete(f'/tasks/{task_id}')
  452.     print(f"[PR10] DELETE /tasks/{task_id}")
  453.     assert resp.status_code == 200
  454.     assert resp.get_json()['message'] == 'Задача успешно удалена'
  455.  
  456.     resp = client.get(f'/tasks/{task_id}')
  457.     assert resp.status_code == 404
  458.  
  459. #------------------------------------------------------------------------------------------
  460. pytest.ini
  461. [pytest]
  462. markers =
  463.     pr2: Практическая работа №2
  464.     pr3: Практическая работа №3
  465.     pr5: Практическая работа №5
  466.     pr7: Практическая работа №7
  467.     pr10: Практическая работа №10
Advertisement
Add Comment
Please, Sign In to add comment