Skip to content

Test/api unit test#86

Open
seal0112 wants to merge 47 commits intomasterfrom
test/api_unit_test
Open

Test/api unit test#86
seal0112 wants to merge 47 commits intomasterfrom
test/api_unit_test

Conversation

@seal0112
Copy link
Owner

No description provided.

seal0112 and others added 30 commits January 14, 2026 00:04
Split the monolithic stock.py fixture file into 11 separate files
for better organization and maintainability:
- daily_information.py
- balance_sheet.py
- income_sheet.py
- cash_flow.py
- month_revenue.py
- monthly_valuation.py
- stock_commodity.py
- data_update_date.py
- stock_search_counts.py
- earnings_call.py
- recommended_stock.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add tests for GET /api/auth/user_info endpoint
- Fix bug in get_user(): use .one_or_none() instead of .one()
  to properly handle deleted users (returns None instead of raising)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Model tests:
- test_default_update_date: verify default date value
- test_exchange_type_valid_values: verify enum values
- test_save_and_retrieve: database CRUD
- test_relationship_with_daily_information: ORM relationship
- test_cascade_delete: cascade delete behavior

API tests (GET/POST/PATCH):
- GET: existing stock, nonexistent stock (404)
- POST: create, update, no change (200), type conversion,
        empty body, no body, invalid JSON (400)
- PATCH: update exchange_type, nonexistent stock (404),
         empty body, invalid JSON, missing field (400)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…nflict

The tests/models/test_api_token.py and tests/api/test_api_token.py have
the same module name causing pytest import conflicts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add tests/fixtures/auth.py with auth_headers and authenticated_client fixtures
- Update conftest.py to load auth fixtures
- Update test_announcement_income_sheet_analysis_api.py to use authenticated_client
  for endpoints that require JWT authentication

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…alizer

Decimal fields from db.Numeric columns need explicit field definitions
to be properly serialized to JSON. Using fields.Decimal(as_string=True)
for consistency with other serializers (monthly_valuation, etc).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Replace mock patches with authenticated_client fixture for proper
JWT authentication in API token endpoint tests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
API token endpoints require @moderator_required decorator, so tests
need to use a moderator user instead of regular_user.

- Add moderator_auth_headers and moderator_authenticated_client fixtures
- Refactor AuthenticatedClient class to be reusable
- Update all API token tests to use moderator fixtures

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The moderator_user fixture teardown was failing because API tokens
still referenced the user (FK constraint). Now we delete tokens first.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…ures

BasicInformation records have child records (Feed, AnnouncementIncomeSheetAnalysis)
that need to be deleted first due to FK constraints.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Added cleanup for all tables that reference BasicInformation:
- DailyInformation, BalanceSheet, IncomeSheet, MonthRevenue
- MonthlyValuation, FollowStock, RecommendedStock

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fixtures now check if record exists before creating to handle cases
where previous tests failed without proper cleanup.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add cascade delete relationships in BasicInformation for:
  BalanceSheet, IncomeSheet, MonthRevenue, StockSearchCounts
- Remove redundant basic_information relationship from MonthRevenue
- Fix fixture imports: use correct model paths for external modules
  (MonthlyValuation, Follow_Stock, EarningsCall)
- Simplify cleanup_stock_references to only handle non-cascaded models

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add new phase for implementing observability stack:
- Prometheus metrics (Flask exporter, custom metrics)
- Loki log aggregation (structured logging, Promtail)
- Grafana dashboards (API overview, business metrics, logs)
- Alerting rules (error rate, latency, service health)
- Infrastructure setup (docker-compose integration)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Remove nested app_context from all fixtures
- Each fixture now depends on sample_basic_info → app_context chain
- Each fixture only cleans up what it creates (no cascade cleanup)
- Reorder pytest_plugins for clarity
- Extend sample_month_revenue_list to 12 months

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add stock_metrics summary table design
- Add screener template and user_screener table design
- Add screener engine and API endpoints
- Add drag-and-drop UI components checklist

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Replace standard logging with structlog
- Support JSON format (for Loki) and console format (for human reading)
- Add LOG_FORMAT env var to switch between formats (default: console)
- Keep request_id tracking via flask-log-request-id
- Add get_logger() helper function

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix test fixtures to use ApiToken.create_token() instead of
  incorrectly calling generate_token() on instance
- Add is_expired field to ApiToken.to_dict() and Marshmallow schema
- Allows frontend to display token expiration status

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Change date= to target_date= to match service method signatures

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add unique constraint (stock_id, year, season) to income_sheet
- Add unique constraint (stock_id, year, month) to month_revenue
- Migration handles existing duplicates by keeping latest record
- Fix income_sheet fixture month calculation (season 4 was producing month 14)
- Fix basic_information fixture cleanup order (each fixture cleans its own data)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add api_token cleanup to regular_user, user_no_roles, multi_role_user fixtures
- Fix test_get_token_prefix expected value (stk_abc123de, not stk_abc12345)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
seal0112 and others added 17 commits January 18, 2026 19:20
- Add session-scoped clean_test_db fixture to ensure clean DB at test start
- Update basic_information fixtures to delete all FK-referencing tables
  explicitly before deleting parent (14 child tables total)
- Update user fixtures to delete api_token before user
- Fix month_revenue test to expect Enum sort order (numeric) not string sort
- Add cleanup at fixture start to handle leftover data from failed tests

FK deletion order in basic_information fixtures:
1. month_revenue, income_sheet, balance_sheet, cashflow
2. daily_information, monthly_valuation, StockCommodity
3. data_update_date, recommended_stock, feed
4. announcement_income_sheet_analysis, earnings_call
5. follow_stock, stock_search_counts
6. basic_information (parent)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix calculate_ratio to properly handle None values for revenue and ratios
- Return None for 本業佔比 when 稅前淨利率 is None or 0 (avoid division by zero)
- Update tests to expect None instead of 0 for edge cases
- Set 稅前淨利=0 in test instead of manually setting 稅前淨利率=0

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add comprehensive API tests for follow_stock module (27 test cases)
  - CRUD operations, IDOR security tests, response structure validation
- Fix Feed model missing return statement in create_announcement_income_sheet_analysis
- Add module-level table truncation in conftest.py for test isolation
- Fix test fixtures with existence checks to prevent duplicate entry errors
- Update test assertions to match actual database behavior

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Upgrade packages in requirements.txt
- Replace flask-log-request-id with custom implementation for Flask 3.0
- Add app/utils/request_id.py as Flask 3.0 compatible request ID middleware

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Remove unused imports (F401) in multiple files
- Fix None comparisons to use `is None` instead of `== None` (E711)
- Fix type comparisons to use isinstance() (E721)
- Replace bare except clauses with `except Exception` (E722)
- Add new jwt_utils module

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add project documentation file with commands, architecture overview,
testing conventions, and known gotchas to help Claude Code understand
the codebase structure.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add reference to detailed task list and current progress summary
in Work Plans section for better project context tracking.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Implement GET endpoints for balance_sheet and cash_flow (was stub)
- Replace make_response(json.dumps(...)) with jsonify({...})
- Replace Schema.dumps() with jsonify(Schema.dump())
- Replace direct dict returns with jsonify()
- Fix error handlers to return proper JSON format
- Standardize error response format: {"error": "message"}

Affected modules:
- balance_sheet, cash_flow: implement GET + fix errors
- basic_information, income_sheet, month_revenue: Schema.dumps -> jsonify
- follow_stock, push_notification, monthly_valuation: fix responses
- earnings_call, feed, announcement_income_sheet_analysis: fix formats
- auth/errors, frontend/errors, main/stockerControl: standardize

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Mark Phase 2.1 as 100% complete (JSON response format)
- Mark Phase 3.1 balance_sheet/cash_flow stub as done
- Update progress: 27 -> 31 items (21% -> 25%)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
… mock targets

- Migrate serializers from ma.Schema to ma.SQLAlchemyAutoSchema with
  model binding, load_instance=False, and include_fk=True
- Fix JWT identity format: use str(user.id) + additional_claims
- Fix mock targets: patch get_current_user instead of get_jwt_identity

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ule name instead of [root]

Also added missing logger instances in push_notification/view.py and monthly_valuation_services.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
create_user() was missing assign_default_role() call, causing newly
created users to have no roles assigned.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant