Ryo_Shimano Claude Sonnet 4.6 commited on
Commit
bff9db3
·
1 Parent(s): 21cd489

テスト: 自動テストスイートを追加、Flask-Sessionの非推奨警告を修正

Browse files

- tests/ ディレクトリに pytest ベースの単体・結合テスト137件を追加
- test_shift_patterns.py: ShiftPattern のカバー判定・境界値テスト
- test_period_fmt.py: 期間ラベルフォーマットテスト
- test_constants.py: Enum クラスのランク・ラベルテスト
- test_employee.py: Employee モデルのスキル判定テスト
- test_schedule_models.py: ShiftRequest/SchedulePeriod テスト
- test_auth_routes.py: 認証ルート・セキュリティヘッダーテスト
- test_employee_routes.py: 従業員ルートの結合テスト
- web_app.py: SESSION_TYPE="filesystem" を非推奨の SESSION_TYPE="cachelib" +
SESSION_CACHELIB=FileSystemCache(...) に変更し DeprecationWarning を解消

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

tests/__init__.py ADDED
File without changes
tests/conftest.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """pytestの共有フィクスチャ"""
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ import pytest
6
+
7
+ # プロジェクトルートをパスに追加
8
+ sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
9
+
10
+
11
+ @pytest.fixture(scope="session")
12
+ def app():
13
+ """結合テスト用Flaskアプリ(テスト用SQLite・CSRF無効)"""
14
+ import db.database as dbmod
15
+ tmp = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
16
+ tmp.close()
17
+ dbmod.DB_PATH = __import__("pathlib").Path(tmp.name)
18
+
19
+ os.environ.pop("DATABASE_URL", None)
20
+ os.environ.pop("APP_PASSWORD", None)
21
+
22
+ # auth.py はモジュールロード時に APP_PASSWORD を確定するため再ロードする
23
+ import auth
24
+ import importlib
25
+ importlib.reload(auth)
26
+
27
+ from web_app import create_app
28
+ application = create_app()
29
+ application.config.update(
30
+ TESTING=True,
31
+ WTF_CSRF_ENABLED=False,
32
+ SECRET_KEY="test-secret",
33
+ )
34
+ yield application
35
+
36
+ os.unlink(tmp.name)
37
+
38
+
39
+ @pytest.fixture
40
+ def client(app):
41
+ return app.test_client()
tests/test_auth_routes.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 結合テスト: routes/auth_routes.py
3
+ 品質特性: セキュリティ・機能適合性(ISO/IEC 25010 §4.2.6, §4.2.1)
4
+ テストレベル: 結合テスト(Flaskテストクライアント使用)
5
+ """
6
+ import pytest
7
+
8
+
9
+ class TestLoginGet:
10
+ def test_login_page_returns_200(self, client):
11
+ resp = client.get("/login")
12
+ assert resp.status_code == 200
13
+
14
+ def test_login_page_contains_form(self, client):
15
+ resp = client.get("/login")
16
+ html = resp.data.decode("utf-8")
17
+ assert "password" in html.lower() or "login" in html.lower()
18
+
19
+
20
+ class TestLoginPost:
21
+ def test_wrong_password_stays_on_login(self, client, app):
22
+ """APP_PASSWORDが設定されている場合、誤パスワードはログインページに留まる"""
23
+ import auth
24
+ original = auth.APP_PASSWORD
25
+ try:
26
+ auth.APP_PASSWORD = "correct_password"
27
+ resp = client.post(
28
+ "/login",
29
+ data={"password": "wrong_password"},
30
+ follow_redirects=False,
31
+ )
32
+ assert resp.status_code == 200
33
+ finally:
34
+ auth.APP_PASSWORD = original
35
+
36
+ def test_no_password_set_redirects_after_any_post(self, client, app):
37
+ """APP_PASSWORDが空の場合、任意のパスワードでもダッシュボードへリダイレクト"""
38
+ import auth
39
+ original = auth.APP_PASSWORD
40
+ try:
41
+ auth.APP_PASSWORD = ""
42
+ # パスワード無しでも before_request で全開放
43
+ resp = client.get("/", follow_redirects=False)
44
+ assert resp.status_code in (200, 302)
45
+ finally:
46
+ auth.APP_PASSWORD = original
47
+
48
+
49
+ class TestSafeNext:
50
+ """_safe_next のオープンリダイレクト対策"""
51
+
52
+ def _get_safe_next(self, url):
53
+ from routes.auth_routes import _safe_next
54
+ return url
55
+
56
+ def test_relative_path_allowed(self, app):
57
+ with app.app_context():
58
+ from routes.auth_routes import _safe_next
59
+ result = _safe_next("/employees/")
60
+ assert result == "/employees/"
61
+
62
+ def test_external_url_rejected(self, app):
63
+ with app.app_context():
64
+ from routes.auth_routes import _safe_next
65
+ result = _safe_next("https://evil.com")
66
+ assert not result.startswith("http")
67
+
68
+ def test_double_slash_rejected(self, app):
69
+ with app.app_context():
70
+ from routes.auth_routes import _safe_next
71
+ result = _safe_next("//evil.com")
72
+ assert not result.startswith("//")
73
+
74
+ def test_backslash_rejected(self, app):
75
+ with app.app_context():
76
+ from routes.auth_routes import _safe_next
77
+ result = _safe_next("/\\evil.com")
78
+ assert "\\" not in result
79
+
80
+ def test_empty_string_returns_dashboard(self, app):
81
+ with app.app_context():
82
+ from routes.auth_routes import _safe_next
83
+ result = _safe_next("")
84
+ assert result.startswith("/")
85
+
86
+
87
+ class TestLogout:
88
+ def test_logout_redirects_to_login(self, client):
89
+ resp = client.get("/logout", follow_redirects=False)
90
+ assert resp.status_code == 302
91
+ assert "/login" in resp.headers.get("Location", "")
92
+
93
+
94
+ class TestSecurityHeaders:
95
+ """セキュリティヘッダーが全レスポンスに付与される"""
96
+
97
+ def test_x_content_type_options(self, client):
98
+ resp = client.get("/login")
99
+ assert resp.headers.get("X-Content-Type-Options") == "nosniff"
100
+
101
+ def test_x_frame_options(self, client):
102
+ resp = client.get("/login")
103
+ assert resp.headers.get("X-Frame-Options") == "SAMEORIGIN"
104
+
105
+ def test_x_xss_protection(self, client):
106
+ resp = client.get("/login")
107
+ assert "1" in resp.headers.get("X-XSS-Protection", "")
tests/test_constants.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 単体テスト: utils/constants.py
3
+ 品質特性: 機能適合性(ISO/IEC 25010 §4.2.1)
4
+ テストレベル: 単体テスト
5
+ """
6
+ import pytest
7
+ from utils.constants import (
8
+ EmploymentType,
9
+ SkillLevel,
10
+ TimeSlot,
11
+ Position,
12
+ PrimaryPosition,
13
+ SHIFT_CONSTRAINTS,
14
+ )
15
+
16
+
17
+ class TestSkillLevel:
18
+ def test_rank_order(self):
19
+ assert SkillLevel.LEADER.rank() > SkillLevel.VETERAN.rank()
20
+ assert SkillLevel.VETERAN.rank() > SkillLevel.GENERAL.rank()
21
+ assert SkillLevel.GENERAL.rank() > SkillLevel.BEGINNER.rank()
22
+
23
+ def test_leader_rank_is_3(self):
24
+ assert SkillLevel.LEADER.rank() == 3
25
+
26
+ def test_beginner_rank_is_0(self):
27
+ assert SkillLevel.BEGINNER.rank() == 0
28
+
29
+ def test_labels_are_japanese(self):
30
+ assert SkillLevel.LEADER.label() == "リーダー"
31
+ assert SkillLevel.VETERAN.label() == "ベテラン"
32
+ assert SkillLevel.GENERAL.label() == "メンバー"
33
+ assert SkillLevel.BEGINNER.label() == "ビギナー"
34
+
35
+ def test_enum_values(self):
36
+ assert SkillLevel.LEADER.value == "leader"
37
+ assert SkillLevel.BEGINNER.value == "beginner"
38
+
39
+
40
+ class TestTimeSlot:
41
+ def test_breakfast_duration(self):
42
+ assert TimeSlot.BREAKFAST.duration_hours() == 5
43
+
44
+ def test_dinner_duration(self):
45
+ assert TimeSlot.DINNER.duration_hours() == 6
46
+
47
+ def test_breakfast_hours(self):
48
+ assert TimeSlot.BREAKFAST.start_hour() == 6
49
+ assert TimeSlot.BREAKFAST.end_hour() == 11
50
+
51
+ def test_dinner_hours(self):
52
+ assert TimeSlot.DINNER.start_hour() == 17
53
+ assert TimeSlot.DINNER.end_hour() == 23
54
+
55
+ def test_labels(self):
56
+ assert "朝食" in TimeSlot.BREAKFAST.label()
57
+ assert "ディナー" in TimeSlot.DINNER.label()
58
+
59
+ def test_short_labels(self):
60
+ assert TimeSlot.BREAKFAST.short_label() == "朝食"
61
+ assert TimeSlot.DINNER.short_label() == "ディナー"
62
+
63
+
64
+ class TestEmploymentType:
65
+ def test_labels(self):
66
+ assert EmploymentType.FULL_TIME.label() == "正社員"
67
+ assert "アルバイト" in EmploymentType.PART_TIME.label()
68
+
69
+ def test_values(self):
70
+ assert EmploymentType.FULL_TIME.value == "full_time"
71
+ assert EmploymentType.PART_TIME.value == "part_time"
72
+
73
+
74
+ class TestPosition:
75
+ def test_labels(self):
76
+ assert Position.HALL.label() == "ホール"
77
+ assert Position.KITCHEN.label() == "キッチン"
78
+
79
+ def test_values(self):
80
+ assert Position.HALL.value == "hall"
81
+ assert Position.KITCHEN.value == "kitchen"
82
+
83
+
84
+ class TestPrimaryPosition:
85
+ def test_labels(self):
86
+ assert PrimaryPosition.HALL.label() == "ホール専任"
87
+ assert PrimaryPosition.KITCHEN.label() == "キッチン専任"
88
+
89
+ def test_short_labels(self):
90
+ assert PrimaryPosition.HALL.short_label() == "ホール"
91
+ assert PrimaryPosition.KITCHEN.short_label() == "キッチン"
92
+
93
+
94
+ class TestShiftConstraints:
95
+ """シフト制約定数の整合性チェック"""
96
+
97
+ def test_all_four_slots_defined(self):
98
+ assert len(SHIFT_CONSTRAINTS) == 4
99
+
100
+ def test_min_lte_max(self):
101
+ for key, c in SHIFT_CONSTRAINTS.items():
102
+ assert c["min"] <= c["max"], f"{key}: min > max"
103
+
104
+ def test_min_leader_positive(self):
105
+ for key, c in SHIFT_CONSTRAINTS.items():
106
+ assert c["min_leader"] >= 1, f"{key}: min_leader < 1"
107
+
108
+ def test_dinner_kitchen_requires_2_leaders(self):
109
+ from utils.constants import SHIFT_CONSTRAINTS, TimeSlot, Position
110
+ c = SHIFT_CONSTRAINTS[(TimeSlot.DINNER, Position.KITCHEN)]
111
+ assert c["min_leader"] == 2
tests/test_employee.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 単体テスト: models/employee.py
3
+ 品質特性: 機能適合性(ISO/IEC 25010 §4.2.1)
4
+ テストレベル: 単体テスト
5
+ """
6
+ import pytest
7
+ from models.employee import Employee
8
+ from utils.constants import EmploymentType, SkillLevel, PrimaryPosition, TimeSlot, Position
9
+
10
+
11
+ def _make_employee(**kwargs) -> Employee:
12
+ defaults = dict(
13
+ id=1,
14
+ name="テスト太郎",
15
+ employment_type=EmploymentType.PART_TIME,
16
+ hall_skill_breakfast=SkillLevel.BEGINNER,
17
+ hall_skill_dinner=SkillLevel.BEGINNER,
18
+ kitchen_skill_breakfast=SkillLevel.BEGINNER,
19
+ kitchen_skill_dinner=SkillLevel.BEGINNER,
20
+ )
21
+ defaults.update(kwargs)
22
+ return Employee(**defaults)
23
+
24
+
25
+ class TestSkillFor:
26
+ """ポジション×時間帯に対応するスキルを返す"""
27
+
28
+ def test_hall_breakfast(self):
29
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.LEADER)
30
+ assert emp.skill_for(Position.HALL, TimeSlot.BREAKFAST) == SkillLevel.LEADER
31
+
32
+ def test_hall_dinner(self):
33
+ emp = _make_employee(hall_skill_dinner=SkillLevel.VETERAN)
34
+ assert emp.skill_for(Position.HALL, TimeSlot.DINNER) == SkillLevel.VETERAN
35
+
36
+ def test_kitchen_breakfast(self):
37
+ emp = _make_employee(kitchen_skill_breakfast=SkillLevel.GENERAL)
38
+ assert emp.skill_for(Position.KITCHEN, TimeSlot.BREAKFAST) == SkillLevel.GENERAL
39
+
40
+ def test_kitchen_dinner(self):
41
+ emp = _make_employee(kitchen_skill_dinner=SkillLevel.VETERAN)
42
+ assert emp.skill_for(Position.KITCHEN, TimeSlot.DINNER) == SkillLevel.VETERAN
43
+
44
+ def test_string_hall_breakfast(self):
45
+ # Position.HALL の文字列値でも動作する
46
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.LEADER)
47
+ assert emp.skill_for("hall", "breakfast") == SkillLevel.LEADER
48
+
49
+
50
+ class TestIsSkilled:
51
+ """ベテラン以上かどうかの判定"""
52
+
53
+ def test_leader_is_skilled(self):
54
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.LEADER)
55
+ assert emp.is_skilled(Position.HALL, TimeSlot.BREAKFAST) is True
56
+
57
+ def test_veteran_is_skilled(self):
58
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.VETERAN)
59
+ assert emp.is_skilled(Position.HALL, TimeSlot.BREAKFAST) is True
60
+
61
+ def test_general_not_skilled(self):
62
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.GENERAL)
63
+ assert emp.is_skilled(Position.HALL, TimeSlot.BREAKFAST) is False
64
+
65
+ def test_beginner_not_skilled(self):
66
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.BEGINNER)
67
+ assert emp.is_skilled(Position.HALL, TimeSlot.BREAKFAST) is False
68
+
69
+
70
+ class TestIsLeader:
71
+ """リーダーかどうかの判定"""
72
+
73
+ def test_leader_is_leader(self):
74
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.LEADER)
75
+ assert emp.is_leader(Position.HALL, TimeSlot.BREAKFAST) is True
76
+
77
+ def test_veteran_not_leader(self):
78
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.VETERAN)
79
+ assert emp.is_leader(Position.HALL, TimeSlot.BREAKFAST) is False
80
+
81
+ def test_general_not_leader(self):
82
+ emp = _make_employee(hall_skill_breakfast=SkillLevel.GENERAL)
83
+ assert emp.is_leader(Position.HALL, TimeSlot.BREAKFAST) is False
84
+
85
+ def test_kitchen_dinner_leader(self):
86
+ emp = _make_employee(kitchen_skill_dinner=SkillLevel.LEADER)
87
+ assert emp.is_leader(Position.KITCHEN, TimeSlot.DINNER) is True
88
+
89
+
90
+ class TestStaffCategoryRank:
91
+ """シフト表での表示順カテゴリ"""
92
+
93
+ def test_full_time_rank_0(self):
94
+ emp = _make_employee(employment_type=EmploymentType.FULL_TIME)
95
+ assert emp.staff_category_rank() == 0
96
+
97
+ def test_part_time_with_dedicated_position_rank_1(self):
98
+ emp = _make_employee(
99
+ primary_position=PrimaryPosition.HALL,
100
+ can_work_both_positions=False,
101
+ )
102
+ assert emp.staff_category_rank() == 1
103
+
104
+ def test_part_time_kitchen_dedicated_rank_1(self):
105
+ emp = _make_employee(
106
+ primary_position=PrimaryPosition.KITCHEN,
107
+ can_work_both_positions=False,
108
+ )
109
+ assert emp.staff_category_rank() == 1
110
+
111
+ def test_part_time_no_position_rank_2(self):
112
+ emp = _make_employee(primary_position=None)
113
+ assert emp.staff_category_rank() == 2
114
+
115
+ def test_part_time_both_positions_rank_2(self):
116
+ emp = _make_employee(
117
+ primary_position=PrimaryPosition.HALL,
118
+ can_work_both_positions=True,
119
+ )
120
+ assert emp.staff_category_rank() == 2
tests/test_employee_routes.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 結合テスト: routes/employees.py
3
+ 品質特性: 機能適合性・信頼性(ISO/IEC 25010 §4.2.1, §4.2.5)
4
+ テストレベル: 結合テスト(Flaskテストクライアント使用)
5
+ """
6
+ import pytest
7
+
8
+
9
+ class TestEmployeeListPage:
10
+ def test_index_returns_200(self, client):
11
+ resp = client.get("/employees/")
12
+ assert resp.status_code == 200
13
+
14
+ def test_index_contains_html(self, client):
15
+ resp = client.get("/employees/")
16
+ assert b"<html" in resp.data.lower() or b"<!doctype" in resp.data.lower()
17
+
18
+ def test_archive_param_accepted(self, client):
19
+ resp = client.get("/employees/?archive=1")
20
+ assert resp.status_code == 200
21
+
22
+ def test_search_param_accepted(self, client):
23
+ resp = client.get("/employees/?q=テスト")
24
+ assert resp.status_code == 200
25
+
26
+
27
+ class TestEmployeeNewPage:
28
+ def test_new_page_returns_200(self, client):
29
+ resp = client.get("/employees/new")
30
+ assert resp.status_code == 200
31
+
32
+
33
+ class TestEmployeeEditPage:
34
+ def test_nonexistent_employee_redirects(self, client):
35
+ # 存在しない従業員IDはフラッシュ付きで一覧へリダイレクト
36
+ resp = client.get("/employees/99999/edit", follow_redirects=False)
37
+ assert resp.status_code == 302
38
+ assert "/employees" in resp.headers.get("Location", "")
39
+
40
+ def test_nonexistent_employee_flash_message(self, client):
41
+ resp = client.get("/employees/99999/edit", follow_redirects=True)
42
+ assert resp.status_code == 200
43
+
44
+ def test_invalid_id_handled(self, client):
45
+ resp = client.get("/employees/abc/edit")
46
+ assert resp.status_code in (400, 404)
tests/test_period_fmt.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 単体テスト: utils/period_fmt.py
3
+ 品質特性: 機能適合性(ISO/IEC 25010 §4.2.1)
4
+ テストレベル: 単体テスト
5
+ """
6
+ import pytest
7
+ from utils.period_fmt import fmt
8
+
9
+
10
+ class TestFmt:
11
+ """期間ラベルの日本語フォーマット"""
12
+
13
+ def test_same_month(self):
14
+ assert fmt("2025-01-01", "2025-01-31") == "2025年1月(1日〜31日)"
15
+
16
+ def test_same_month_mid_period(self):
17
+ assert fmt("2025-06-10", "2025-06-20") == "2025年6月(10日〜20日)"
18
+
19
+ def test_same_day_single(self):
20
+ assert fmt("2025-06-01", "2025-06-01") == "2025年6月(1日〜1日)"
21
+
22
+ def test_cross_month_same_year(self):
23
+ assert fmt("2025-01-27", "2025-02-10") == "2025年1/27〜2/10"
24
+
25
+ def test_cross_month_start_of_month_to_next(self):
26
+ assert fmt("2025-03-31", "2025-04-01") == "2025年3/31〜4/1"
27
+
28
+ def test_cross_year(self):
29
+ assert fmt("2024-12-28", "2025-01-10") == "2024/12/28〜2025/1/10"
30
+
31
+ def test_cross_year_new_year(self):
32
+ assert fmt("2023-12-01", "2024-01-31") == "2023/12/1〜2024/1/31"
33
+
34
+ def test_february_to_march(self):
35
+ assert fmt("2025-02-15", "2025-03-15") == "2025年2/15〜3/15"
36
+
37
+ def test_returns_string(self):
38
+ result = fmt("2025-04-01", "2025-04-30")
39
+ assert isinstance(result, str)
tests/test_schedule_models.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 単体テスト: models/schedule.py (ShiftRequest, SchedulePeriod)
3
+ 品質特性: 機能適合性(ISO/IEC 25010 §4.2.1)
4
+ テストレベル: 単体テスト
5
+ """
6
+ import pytest
7
+ from datetime import date
8
+ from models.schedule import ShiftRequest, ShiftAssignment, SchedulePeriod
9
+ from utils.constants import TimeSlot, Position
10
+
11
+
12
+ class TestShiftRequestSlotCoverage:
13
+ """breakfast / dinner プロパティ(スロットカバー判定)"""
14
+
15
+ def test_b_std_covers_breakfast_only(self):
16
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="b_std")
17
+ assert req.breakfast is True
18
+ assert req.dinner is False
19
+
20
+ def test_d_std1_covers_dinner_only(self):
21
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="d_std1")
22
+ assert req.breakfast is False
23
+ assert req.dinner is True
24
+
25
+ def test_double_covers_both(self):
26
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="double")
27
+ assert req.breakfast is True
28
+ assert req.dinner is True
29
+
30
+ def test_no_pattern_covers_none(self):
31
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id=None)
32
+ assert req.breakfast is False
33
+ assert req.dinner is False
34
+
35
+ def test_am_only_covers_breakfast(self):
36
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="am_only")
37
+ assert req.breakfast is True
38
+ assert req.dinner is False
39
+
40
+ def test_pm_only_covers_dinner(self):
41
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="pm_only")
42
+ assert req.breakfast is False
43
+ assert req.dinner is True
44
+
45
+ def test_custom_breakfast_hours(self):
46
+ req = ShiftRequest(
47
+ employee_id=1, date="2025-01-01",
48
+ pattern_id="custom",
49
+ custom_start="06:00", custom_end="11:00",
50
+ )
51
+ assert req.breakfast is True
52
+ assert req.dinner is False
53
+
54
+ def test_custom_dinner_hours(self):
55
+ req = ShiftRequest(
56
+ employee_id=1, date="2025-01-01",
57
+ pattern_id="custom",
58
+ custom_start="17:00", custom_end="23:00",
59
+ )
60
+ assert req.breakfast is False
61
+ assert req.dinner is True
62
+
63
+ def test_custom_missing_times_covers_none(self):
64
+ req = ShiftRequest(
65
+ employee_id=1, date="2025-01-01",
66
+ pattern_id="custom",
67
+ )
68
+ assert req.breakfast is False
69
+ assert req.dinner is False
70
+
71
+ def test_unknown_pattern_id_covers_none(self):
72
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="nonexistent")
73
+ assert req.breakfast is False
74
+ assert req.dinner is False
75
+
76
+
77
+ class TestShiftRequestHasShift:
78
+ def test_with_pattern_has_shift(self):
79
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="b_std")
80
+ assert req.has_shift is True
81
+
82
+ def test_without_pattern_no_shift(self):
83
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id=None)
84
+ assert req.has_shift is False
85
+
86
+ def test_empty_string_pattern_no_shift(self):
87
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="")
88
+ assert req.has_shift is False
89
+
90
+
91
+ class TestShiftRequestDisplayTime:
92
+ def test_custom_displays_times(self):
93
+ req = ShiftRequest(
94
+ employee_id=1, date="2025-01-01",
95
+ pattern_id="custom",
96
+ custom_start="09:00", custom_end="15:00",
97
+ )
98
+ assert req.display_time() == "09:00〜15:00"
99
+
100
+ def test_custom_missing_start(self):
101
+ req = ShiftRequest(
102
+ employee_id=1, date="2025-01-01",
103
+ pattern_id="custom",
104
+ custom_end="15:00",
105
+ )
106
+ assert "?" in req.display_time()
107
+
108
+ def test_known_pattern_returns_range(self):
109
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id="b_std")
110
+ assert req.display_time() == "06:30〜11:30"
111
+
112
+ def test_no_pattern_returns_empty(self):
113
+ req = ShiftRequest(employee_id=1, date="2025-01-01", pattern_id=None)
114
+ assert req.display_time() == ""
115
+
116
+
117
+ class TestSchedulePeriodDateRange:
118
+ """date_range() の日付リスト生成"""
119
+
120
+ def test_single_day(self):
121
+ period = SchedulePeriod(id=1, start_date="2025-01-01", end_date="2025-01-01")
122
+ dates = period.date_range()
123
+ assert len(dates) == 1
124
+ assert dates[0] == date(2025, 1, 1)
125
+
126
+ def test_three_days(self):
127
+ period = SchedulePeriod(id=1, start_date="2025-01-01", end_date="2025-01-03")
128
+ dates = period.date_range()
129
+ assert len(dates) == 3
130
+ assert dates[0] == date(2025, 1, 1)
131
+ assert dates[-1] == date(2025, 1, 3)
132
+
133
+ def test_cross_month(self):
134
+ # 1/30〜2/3 → 5日間
135
+ period = SchedulePeriod(id=1, start_date="2025-01-30", end_date="2025-02-03")
136
+ dates = period.date_range()
137
+ assert len(dates) == 5
138
+ assert dates[0] == date(2025, 1, 30)
139
+ assert dates[-1] == date(2025, 2, 3)
140
+
141
+ def test_full_month_january(self):
142
+ period = SchedulePeriod(id=1, start_date="2025-01-01", end_date="2025-01-31")
143
+ assert len(period.date_range()) == 31
144
+
145
+ def test_result_is_sorted_ascending(self):
146
+ period = SchedulePeriod(id=1, start_date="2025-03-01", end_date="2025-03-07")
147
+ dates = period.date_range()
148
+ assert dates == sorted(dates)
149
+
150
+ def test_returns_date_objects(self):
151
+ period = SchedulePeriod(id=1, start_date="2025-06-01", end_date="2025-06-02")
152
+ for d in period.date_range():
153
+ assert isinstance(d, date)
tests/test_shift_patterns.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 単体テスト: utils/shift_patterns.py
3
+ 品質特性: 機能適合性(ISO/IEC 25010 §4.2.1)
4
+ テストレベル: 単体テスト
5
+ """
6
+ import pytest
7
+ from utils.shift_patterns import (
8
+ ShiftPattern,
9
+ ALL_PATTERNS,
10
+ PATTERN_MAP,
11
+ is_long_breakfast_pattern,
12
+ default_pattern_from_fixed,
13
+ BREAKFAST_START,
14
+ BREAKFAST_END,
15
+ DINNER_START,
16
+ DINNER_END,
17
+ MIN_OVERLAP_HRS,
18
+ LONG_BREAKFAST_END_HOUR,
19
+ )
20
+
21
+
22
+ class TestShiftPatternToHour:
23
+ def test_whole_hour(self):
24
+ sp = ShiftPattern("t", "テスト", "06:00", "10:00")
25
+ assert sp.start_hour() == 6.0
26
+
27
+ def test_half_hour(self):
28
+ sp = ShiftPattern("t", "テスト", "06:30", "11:30")
29
+ assert sp.start_hour() == 6.5
30
+
31
+ def test_quarter_hour(self):
32
+ sp = ShiftPattern("t", "テスト", "05:45", "14:45")
33
+ assert sp.start_hour() == pytest.approx(5.75)
34
+ assert sp.end_hour() == pytest.approx(14.75)
35
+
36
+ def test_none_returns_none(self):
37
+ sp = ShiftPattern("t", "テスト", None, None)
38
+ assert sp.start_hour() is None
39
+ assert sp.end_hour() is None
40
+
41
+
42
+ class TestCoversBreakfast:
43
+ """朝食時間帯(6:00-11:00)カバー判定"""
44
+
45
+ def test_breakfast_standard_covers(self):
46
+ p = PATTERN_MAP["b_std"] # 6:30-11:30 → 重複4.5h
47
+ assert p.covers_breakfast() is True
48
+
49
+ def test_breakfast_short_covers(self):
50
+ p = PATTERN_MAP["b_short"] # 6:00-10:00 → 重複4h
51
+ assert p.covers_breakfast() is True
52
+
53
+ def test_dinner_only_no_cover(self):
54
+ p = PATTERN_MAP["d_std1"] # 17:00-22:30
55
+ assert p.covers_breakfast() is False
56
+
57
+ def test_double_force_both(self):
58
+ p = PATTERN_MAP["double"]
59
+ assert p.covers_breakfast() is True
60
+
61
+ def test_custom_no_times_no_cover(self):
62
+ p = PATTERN_MAP["custom"]
63
+ assert p.covers_breakfast() is False
64
+
65
+ def test_boundary_exactly_min_overlap(self):
66
+ # 9:00-11:00 → 重複 exactly 2.0h → カバー
67
+ sp = ShiftPattern("t", "テスト", "09:00", "11:00")
68
+ assert sp.covers_breakfast() is True
69
+
70
+ def test_below_min_overlap_no_cover(self):
71
+ # 9:01-11:00 → 重複 1.983h < 2.0h → カバーなし
72
+ sp = ShiftPattern("t", "テスト", "09:01", "11:00")
73
+ assert sp.covers_breakfast() is False
74
+
75
+ def test_dinner_full_covers_breakfast_if_start_early_enough(self):
76
+ # 通し早番 13:00-22:30 → 朝食との重複なし
77
+ p = PATTERN_MAP["d_full1"]
78
+ assert p.covers_breakfast() is False
79
+
80
+
81
+ class TestCoversDinner:
82
+ """ディナー時間帯(17:00-23:00)カバー判定"""
83
+
84
+ def test_dinner_std_covers(self):
85
+ p = PATTERN_MAP["d_std1"] # 17:00-22:30 → 重複5.5h
86
+ assert p.covers_dinner() is True
87
+
88
+ def test_breakfast_no_cover(self):
89
+ p = PATTERN_MAP["b_std"]
90
+ assert p.covers_dinner() is False
91
+
92
+ def test_double_force_both(self):
93
+ p = PATTERN_MAP["double"]
94
+ assert p.covers_dinner() is True
95
+
96
+ def test_custom_no_times_no_cover(self):
97
+ p = PATTERN_MAP["custom"]
98
+ assert p.covers_dinner() is False
99
+
100
+ def test_boundary_exactly_min_overlap(self):
101
+ # 17:00-19:00 → 重複 exactly 2.0h → カバー
102
+ sp = ShiftPattern("t", "テスト", "17:00", "19:00")
103
+ assert sp.covers_dinner() is True
104
+
105
+ def test_below_min_overlap_no_cover(self):
106
+ # 17:01-19:00 → 重複 1.983h < 2.0h
107
+ sp = ShiftPattern("t", "テスト", "17:01", "19:00")
108
+ assert sp.covers_dinner() is False
109
+
110
+ def test_through_shift_covers_dinner(self):
111
+ # 通し遅番 14:00-23:00
112
+ p = PATTERN_MAP["d_full2"]
113
+ assert p.covers_dinner() is True
114
+
115
+
116
+ class TestDurationHours:
117
+ """実勤務時間計算"""
118
+
119
+ def test_double_returns_11(self):
120
+ assert PATTERN_MAP["double"].duration_hours() == 11.0
121
+
122
+ def test_custom_no_times_returns_zero(self):
123
+ assert PATTERN_MAP["custom"].duration_hours() == 0.0
124
+
125
+ def test_b_std_5hours(self):
126
+ p = PATTERN_MAP["b_std"] # 6:30-11:30
127
+ assert p.duration_hours() == pytest.approx(5.0)
128
+
129
+ def test_d_std1_5point5hours(self):
130
+ p = PATTERN_MAP["d_std1"] # 17:00-22:30
131
+ assert p.duration_hours() == pytest.approx(5.5)
132
+
133
+ def test_b_long_9hours(self):
134
+ p = PATTERN_MAP["b_long"] # 5:45-14:45
135
+ assert p.duration_hours() == pytest.approx(9.0)
136
+
137
+
138
+ class TestTimeRangeLabel:
139
+ """表示用時刻文字列"""
140
+
141
+ def test_double(self):
142
+ assert PATTERN_MAP["double"].time_range_label() == "6:00〜11:00 / 17:00〜23:00"
143
+
144
+ def test_b_std(self):
145
+ assert PATTERN_MAP["b_std"].time_range_label() == "06:30〜11:30"
146
+
147
+ def test_custom_no_times(self):
148
+ assert PATTERN_MAP["custom"].time_range_label() == ""
149
+
150
+
151
+ class TestAllPatternsConsistency:
152
+ """ALL_PATTERNSの整合性チェック"""
153
+
154
+ def test_all_ids_unique(self):
155
+ ids = [p.id for p in ALL_PATTERNS]
156
+ assert len(ids) == len(set(ids))
157
+
158
+ def test_pattern_map_matches_all_patterns(self):
159
+ for p in ALL_PATTERNS:
160
+ assert PATTERN_MAP[p.id] is p
161
+
162
+ def test_non_custom_patterns_have_label(self):
163
+ for p in ALL_PATTERNS:
164
+ assert p.label, f"{p.id} has empty label"
165
+
166
+
167
+ class TestIsLongBreakfastPattern:
168
+ """朝食ロング勤務判定"""
169
+
170
+ def test_b_long_is_long(self):
171
+ # 5:45-14:45 → 朝食カバー・終了14.75 >= 14.0
172
+ assert is_long_breakfast_pattern("b_long") is True
173
+
174
+ def test_b_8h_is_long(self):
175
+ # 6:00-14:00 → 終了14.0 >= 14.0
176
+ assert is_long_breakfast_pattern("b_8h") is True
177
+
178
+ def test_b_half_is_long(self):
179
+ # 6:30-15:30 → 終了15.5 >= 14.0
180
+ assert is_long_breakfast_pattern("b_half") is True
181
+
182
+ def test_b_std_not_long(self):
183
+ # 6:30-11:30 → 終了11.5 < 14.0
184
+ assert is_long_breakfast_pattern("b_std") is False
185
+
186
+ def test_b_short_not_long(self):
187
+ # 6:00-10:00 → 終了10.0 < 14.0
188
+ assert is_long_breakfast_pattern("b_short") is False
189
+
190
+ def test_dinner_not_long(self):
191
+ assert is_long_breakfast_pattern("d_std1") is False
192
+
193
+ def test_none_pattern_id(self):
194
+ assert is_long_breakfast_pattern(None) is False
195
+
196
+ def test_custom_long(self):
197
+ assert is_long_breakfast_pattern("custom", "06:00", "15:00") is True
198
+
199
+ def test_custom_short(self):
200
+ assert is_long_breakfast_pattern("custom", "06:00", "11:00") is False
201
+
202
+ def test_custom_missing_times(self):
203
+ assert is_long_breakfast_pattern("custom") is False
204
+
205
+ def test_custom_dinner_not_long(self):
206
+ assert is_long_breakfast_pattern("custom", "17:00", "23:00") is False
207
+
208
+
209
+ class TestDefaultPatternFromFixed:
210
+ """固定フラグからデフォルトパターンID変換"""
211
+
212
+ def test_both_true_returns_double(self):
213
+ assert default_pattern_from_fixed(True, True) == "double"
214
+
215
+ def test_breakfast_only_returns_b_std(self):
216
+ assert default_pattern_from_fixed(True, False) == "b_std"
217
+
218
+ def test_dinner_only_returns_d_std1(self):
219
+ assert default_pattern_from_fixed(False, True) == "d_std1"
220
+
221
+ def test_both_false_returns_none(self):
222
+ assert default_pattern_from_fixed(False, False) is None
web_app.py CHANGED
@@ -45,12 +45,13 @@ def create_app():
45
  CSRFProtect(app)
46
 
47
  # サーバーサイドセッション(ファイルストア)
48
- # Flask-Session 0.8.x では SESSION_PERMANENT / SESSION_USE_SIGNER は廃止
49
- os.makedirs("/tmp/flask_sessions", exist_ok=True)
 
 
50
  app.config.update(
51
- SESSION_TYPE="filesystem",
52
- SESSION_FILE_DIR="/tmp/flask_sessions",
53
- SESSION_FILE_THRESHOLD=500,
54
  PERMANENT_SESSION_LIFETIME=timedelta(days=30),
55
  SESSION_COOKIE_SECURE=not is_dev,
56
  SESSION_COOKIE_HTTPONLY=True,
 
45
  CSRFProtect(app)
46
 
47
  # サーバーサイドセッション(ファイルストア)
48
+ # Flask-Session 0.8.x では SESSION_TYPE="cachelib" + SESSION_CACHELIB が推奨
49
+ from cachelib import FileSystemCache
50
+ session_dir = "/tmp/flask_sessions"
51
+ os.makedirs(session_dir, exist_ok=True)
52
  app.config.update(
53
+ SESSION_TYPE="cachelib",
54
+ SESSION_CACHELIB=FileSystemCache(cache_dir=session_dir, threshold=500),
 
55
  PERMANENT_SESSION_LIFETIME=timedelta(days=30),
56
  SESSION_COOKIE_SECURE=not is_dev,
57
  SESSION_COOKIE_HTTPONLY=True,