From 530cb7930c5319bd067ae381c8587e1ba9d22908 Mon Sep 17 00:00:00 2001 From: utahta Date: Sun, 19 Jul 2026 09:42:39 +0900 Subject: [PATCH 1/2] Resolve e2e test dates dynamically from the trading calendar The suite relied on a hardcoded trading day (20250613), which would break for every date-based test once it left a plan's data retention window. TestMain now resolves recent trading days via the trading calendar API (weekday fallback if unavailable) with a configurable lag (JQUANTS_TEST_LAG_DAYS, rejected loudly when invalid). When no lag is specified, a one-shot probe against the daily quotes API detects delayed plans (valid queries return empty data, never an error) and falls back to a 13-week lag so Free-plan runs still exercise the endpoints; probe errors fail the run instead of being misdiagnosed as a plan limitation. --- test/e2e/e2e_test.go | 146 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 138 insertions(+), 8 deletions(-) diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index c722ada..8a90e44 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -4,17 +4,23 @@ package e2e import ( + "context" "fmt" "os" + "sort" + "strconv" "strings" "testing" + "time" "github.com/utahta/jquants" "github.com/utahta/jquants/client" ) var ( - jq *jquants.JQuantsAPI + jq *jquants.JQuantsAPI + testDate string // テストで使用する直近営業日(YYYYMMDD形式) + tradingDays []string // 直近の営業日一覧(YYYYMMDD形式、新しい順) ) func TestMain(m *testing.M) { @@ -30,10 +36,123 @@ func TestMain(m *testing.M) { // JQuantsAPI作成 jq = jquants.NewJQuantsAPI(c) + // テストで使用する営業日を決定 + resolveTestDate() + // テスト実行 os.Exit(m.Run()) } +// testLagDays はテスト基準日を何日前にするかと、環境変数 +// JQUANTS_TEST_LAG_DAYS で明示的に指定されたかどうかを返す。 +// デフォルトはデータの公表ラグを考慮した4日。不正な値が設定されている場合は +// タイポを黙って無視しないようpanicする。 +func testLagDays() (int, bool) { + v := os.Getenv("JQUANTS_TEST_LAG_DAYS") + if v == "" { + return 4, false + } + n, err := strconv.Atoi(v) + if err != nil || n <= 0 { + panic(fmt.Sprintf("invalid JQUANTS_TEST_LAG_DAYS %q: must be a positive integer", v)) + } + return n, true +} + +// resolveTestDate はテストで使用する営業日を決定する。 +// まずデフォルトのラグで営業日を選び、その日付のデータが実際に取得できるかを +// 確認する。データ遅延のあるプラン(Freeプランは12週遅延)で取得できない場合は +// 13週前のラグに自動で切り替える。JQUANTS_TEST_LAG_DAYS が明示されている場合は +// そのラグをそのまま使用する。 +func resolveTestDate() { + lag, explicit := testLagDays() + resolveTradingDaysWithLag(lag) + + if explicit { + return + } + available, err := dataAvailable(testDate) + if err != nil { + // プローブのエラーは遅延プランの空データとは別問題(ネットワーク・認証・ + // クエリのリグレッション等)なので、フォールバックで隠さず即失敗させる + panic(fmt.Sprintf("e2e: failed to probe data availability for %s: %v", testDate, err)) + } + if !available { + const delayedPlanLagDays = 13 * 7 + fmt.Printf("e2e: data for %s is not accessible on this plan; retrying with %d-day lag\n", + testDate, delayedPlanLagDays) + resolveTradingDaysWithLag(delayedPlanLagDays) + } +} + +// resolveTradingDaysWithLag は取引カレンダーAPIから「lagDays日前まで」の直近の +// 営業日一覧を取得してtradingDaysとtestDateに設定する。カレンダーの取得に +// 失敗した場合は、土日を除いた直近の平日にフォールバックする。 +func resolveTradingDaysWithLag(lagDays int) { + tradingDays = nil + to := time.Now().AddDate(0, 0, -lagDays) + from := to.AddDate(0, 0, -21) + + days, err := jq.TradingCalendar.GetTradingDays(context.Background(), + from.Format("20060102"), to.Format("20060102")) + if err == nil && len(days) > 0 { + dates := make([]string, 0, len(days)) + for _, d := range days { + dates = append(dates, strings.ReplaceAll(d.Date, "-", "")) + } + sort.Sort(sort.Reverse(sort.StringSlice(dates))) + tradingDays = dates + testDate = tradingDays[0] + fmt.Printf("e2e test date: %s (from trading calendar)\n", testDate) + return + } + + // フォールバック: 土日を除いた直近の平日(祝日は考慮できない) + for d := to; len(tradingDays) < 10; d = d.AddDate(0, 0, -1) { + if d.Weekday() != time.Saturday && d.Weekday() != time.Sunday { + tradingDays = append(tradingDays, d.Format("20060102")) + } + } + testDate = tradingDays[0] + fmt.Printf("e2e test date: %s (weekday fallback; calendar error: %v)\n", testDate, err) +} + +// dataAvailable は指定日の株価データが現在のプランで取得可能かを確認する。 +// 株価四本値APIは全プランで利用可能なため、プローブとして使用する。 +// 有効なクエリでデータがない場合、APIはエラーではなく空データを返すため、 +// 「エラーなし・空データ」だけが取得不可(データ遅延プラン)を意味する。 +func dataAvailable(date string) (bool, error) { + resp, err := jq.Quotes.GetDailyQuotes(context.Background(), + jquants.DailyQuotesParams{Code: "72030", Date: date}) + if err != nil { + return false, err + } + return resp != nil && len(resp.Data) > 0, nil +} + +// findPopulatedTestDate は直近の営業日から順に最大maxDays日分countFnを呼び、 +// データが存在した最初の営業日を返す。開示・公表がある日にのみデータが存在する +// イベント駆動のデータセットのテストで使用する。見つからない場合は空文字を返す。 +func findPopulatedTestDate(t *testing.T, maxDays int, countFn func(date string) (int, error)) string { + t.Helper() + for i, date := range tradingDays { + if i >= maxDays { + break + } + n, err := countFn(date) + if err != nil { + if isSubscriptionLimited(err) { + t.Skip("Skipping due to subscription limitation") + } + t.Fatalf("Failed to fetch data for %s: %v", date, err) + } + if n > 0 { + return date + } + } + return "" +} + // isSubscriptionLimited はサブスクリプションプランによる制限があるかをチェックする func isSubscriptionLimited(err error) bool { if err == nil { @@ -45,17 +164,28 @@ func isSubscriptionLimited(err error) bool { strings.Contains(errMsg, "not available on your subscription") } -// getTestDate はテスト用の固定営業日を取得する +// getTestDate はテストで使用する直近営業日をYYYYMMDD形式で取得する func getTestDate() string { - // 2025年6月13日(金曜日)を返す - // これにより、テストの一貫性とデータの存在を保証 - return "20250613" + return testDate } -// getTestDateFormatted はテスト用の固定営業日をYYYY-MM-DD形式で取得する +// getTestDateFormatted はテストで使用する直近営業日をYYYY-MM-DD形式で取得する func getTestDateFormatted() string { - // APIレスポンスで使用されるYYYY-MM-DD形式で返す - return "2025-06-13" + return formatDate(testDate) +} + +// formatDate はYYYYMMDD形式の日付をYYYY-MM-DD形式に変換する +func formatDate(date string) string { + return date[:4] + "-" + date[4:6] + "-" + date[6:] +} + +// getTestDateDaysAgo はテスト基準日のn日前をYYYYMMDD形式で取得する +func getTestDateDaysAgo(n int) string { + d, err := time.Parse("20060102", testDate) + if err != nil { + panic(fmt.Sprintf("invalid testDate %q: %v", testDate, err)) + } + return d.AddDate(0, 0, -n).Format("20060102") } // fmtPrice はnil許容の価格フィールドをログ表示用に整形する From 06a61ba5f404b4f5b047198d03f05633481b2a0e Mon Sep 17 00:00:00 2001 From: utahta Date: Sun, 19 Jul 2026 09:42:39 +0900 Subject: [PATCH 2/2] Make e2e tests fail on unexpected errors and validate populated data Eleven subtests logged API errors and returned silently, so they never verified their success paths (the pattern that hid the invalid indices query fixed earlier). Unexpected errors now fail the test; skips remain only for subscription limits and legitimately empty datasets, since the API returns 200 with empty data rather than 4xx when a valid query has no data. Event-driven datasets no longer depend on the run date: statements and fs_details resolve a recent disclosure day via findPopulatedTestDate, and the investor-types single-day query targets the latest publication date found in a 30-day range (from/to filter on publication date), failing instead of skipping when that date returns nothing. This surfaced two dead spots: section "All" is not a valid investor-types section (now TokyoNagoya) and the single-day query never matched period dates. Also derive the daily margin interest range start from the resolved test date instead of a fixed 20250601. --- test/e2e/announcement_test.go | 7 +- test/e2e/breakdown_test.go | 3 +- test/e2e/daily_margin_interest_test.go | 5 +- test/e2e/daily_quotes_test.go | 3 +- test/e2e/fs_details_test.go | 30 +++----- test/e2e/indices_test.go | 3 +- test/e2e/prices_am_test.go | 3 +- test/e2e/short_selling_positions_test.go | 64 ++++++++-------- test/e2e/short_selling_test.go | 66 ++++++++-------- test/e2e/statements_test.go | 95 ++++++++++++------------ test/e2e/topix_test.go | 3 +- test/e2e/trades_spec_test.go | 47 +++++++----- test/e2e/trading_calendar_test.go | 6 +- test/e2e/weekly_margin_interest_test.go | 3 +- 14 files changed, 164 insertions(+), 174 deletions(-) diff --git a/test/e2e/announcement_test.go b/test/e2e/announcement_test.go index 4e9ba70..acdbbe3 100644 --- a/test/e2e/announcement_test.go +++ b/test/e2e/announcement_test.go @@ -20,9 +20,7 @@ func TestAnnouncementEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - // 決算発表予定がない日の可能性もある - t.Logf("No announcement data (might be no announcements): %v", err) - return + t.Fatalf("Failed to get announcements: %v", err) } if resp == nil || len(resp.Data) == 0 { @@ -133,8 +131,7 @@ func TestAnnouncementEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("No announcement data for date %s: %v", date, err) - return + t.Fatalf("Failed to get announcements for date %s: %v", date, err) } if resp != nil && len(resp.Data) > 0 { diff --git a/test/e2e/breakdown_test.go b/test/e2e/breakdown_test.go index ebc6a54..3016825 100644 --- a/test/e2e/breakdown_test.go +++ b/test/e2e/breakdown_test.go @@ -129,8 +129,7 @@ func TestBreakdownEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") } - t.Logf("Failed to get breakdown by date: %v", err) - return + t.Fatalf("Failed to get breakdown by date: %v", err) } if resp == nil || len(resp.Data) == 0 { diff --git a/test/e2e/daily_margin_interest_test.go b/test/e2e/daily_margin_interest_test.go index 5e2b350..c2ebe60 100644 --- a/test/e2e/daily_margin_interest_test.go +++ b/test/e2e/daily_margin_interest_test.go @@ -119,8 +119,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get daily margin interest by date: %v", err) - return + t.Fatalf("Failed to get daily margin interest by date: %v", err) } if resp == nil || len(resp.Data) == 0 { @@ -236,7 +235,7 @@ func TestDailyMarginInterestEndpoint(t *testing.T) { t.Run("GetDailyMarginInterestByCodeAndDateRange", func(t *testing.T) { // 期間指定のテスト to := getTestDate() - from := "20250601" // 約2週間分 + from := getTestDateDaysAgo(14) // 約2週間分 interests, err := jq.DailyMarginInterest.GetDailyMarginInterestByCodeAndDateRange(context.Background(), "13260", from, to) if err != nil { diff --git a/test/e2e/daily_quotes_test.go b/test/e2e/daily_quotes_test.go index 5ce4bf9..937d1ad 100644 --- a/test/e2e/daily_quotes_test.go +++ b/test/e2e/daily_quotes_test.go @@ -174,8 +174,7 @@ func TestDailyQuotesEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("No quotes data for date %s: %v", date, err) - return + t.Fatalf("Failed to get quotes for date %s: %v", date, err) } if resp == nil || len(resp.Data) == 0 { diff --git a/test/e2e/fs_details_test.go b/test/e2e/fs_details_test.go index c40670b..def742d 100644 --- a/test/e2e/fs_details_test.go +++ b/test/e2e/fs_details_test.go @@ -194,24 +194,18 @@ func TestFSDetailsEndpoint(t *testing.T) { }) t.Run("GetFSDetails_ByDate", func(t *testing.T) { - // 最近の営業日の財務詳細を取得 - date := getTestDate() - - params := jquants.FSDetailsParams{ - Date: date, - } - - details, err := jq.FSDetails.GetFSDetails(context.Background(), params) - if err != nil { - if isSubscriptionLimited(err) { - t.Skip("Skipping due to subscription limitation (expected for premium API)") + // 開示は毎営業日あるとは限らないため、開示がある営業日を直近から探す + var details *jquants.FSDetailsResponse + date := findPopulatedTestDate(t, 5, func(d string) (int, error) { + var err error + details, err = jq.FSDetails.GetFSDetails(context.Background(), jquants.FSDetailsParams{Date: d}) + if details == nil { + return 0, err } - t.Logf("Failed to get FS details by date: %v", err) - return - } - - if details == nil || len(details.Data) == 0 { - t.Skip("No FS details data for the specified date") + return len(details.Data), err + }) + if date == "" { + t.Skip("No FS details found on recent trading days") } t.Logf("Retrieved %d FS details records for %s", len(details.Data), date) @@ -219,7 +213,7 @@ func TestFSDetailsEndpoint(t *testing.T) { // 日付の一致確認 for i, detail := range details.Data { // 日付形式をYYYY-MM-DDに統一して比較 - expectedDate := getTestDateFormatted() + expectedDate := formatDate(date) if detail.DiscDate != expectedDate { t.Errorf("Detail[%d]: DisclosedDate = %v, want %v", i, detail.DiscDate, expectedDate) diff --git a/test/e2e/indices_test.go b/test/e2e/indices_test.go index 5c47dcb..a3d8352 100644 --- a/test/e2e/indices_test.go +++ b/test/e2e/indices_test.go @@ -126,8 +126,7 @@ func TestIndicesEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get indices with code filter: %v", err) - return + t.Fatalf("Failed to get indices with code filter: %v", err) } if resp != nil && len(resp.Data) > 0 { diff --git a/test/e2e/prices_am_test.go b/test/e2e/prices_am_test.go index 624d596..e6cf233 100644 --- a/test/e2e/prices_am_test.go +++ b/test/e2e/prices_am_test.go @@ -125,8 +125,7 @@ func TestPricesAMEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation (expected for premium API)") } - t.Logf("Failed to get prices AM by date: %v", err) - return + t.Fatalf("Failed to get prices AM: %v", err) } if resp == nil || len(resp.Data) == 0 { diff --git a/test/e2e/short_selling_positions_test.go b/test/e2e/short_selling_positions_test.go index cc75e67..b40a217 100644 --- a/test/e2e/short_selling_positions_test.go +++ b/test/e2e/short_selling_positions_test.go @@ -40,13 +40,13 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { if position.SSName == "" { t.Errorf("Position[%d]: ShortSellerName is empty", i) } - + // 日付の妥当性チェック if position.DiscDate < position.CalcDate { t.Errorf("Position[%d]: DisclosedDate (%s) < CalculatedDate (%s)", i, position.DiscDate, position.CalcDate) } - + // 残高割合の検証(通常0.5%以上で報告義務) if position.ShrtPosToSO < 0.5 { t.Logf("Position[%d]: Low ratio: %.2f%% (might be below reporting threshold)", @@ -56,7 +56,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { t.Errorf("Position[%d]: Extremely high ratio: %.2f%%", i, position.ShrtPosToSO) } - + // 株数の検証 if position.ShrtPosShares <= 0 { t.Errorf("Position[%d]: ShortPositionsInSharesNumber = %v, want > 0", @@ -66,12 +66,12 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { t.Errorf("Position[%d]: ShortPositionsInTradingUnitsNumber = %v, want > 0", i, position.ShrtPosUnits) } - + // 住所情報の検証(オプショナル) if position.SSAddr == "" { t.Logf("Position[%d]: ShortSellerAddress is empty", i) } - + // 投資一任契約の情報確認 hasDiscretionary := position.HasDiscretionaryInvestment() if hasDiscretionary { @@ -83,19 +83,19 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { t.Logf(" Fund: %s", position.FundName) } } - + // 個人投資家かチェック if position.IsIndividual() { t.Logf("Position[%d]: Individual investor", i) } - + // 最初の5件の詳細ログ if i < 5 { t.Logf("Position[%d]: %s", i, position.SSName) t.Logf(" Disclosed: %s, Calculated: %s", position.DiscDate, position.CalcDate) - t.Logf(" Ratio: %.2f%%, Shares: %.0f", + t.Logf(" Ratio: %.2f%%, Shares: %.0f", position.ShrtPosToSO, position.ShrtPosShares) - + // 前回からの変化 changeRatio := position.GetPositionChangeRatio() if changeRatio != 0 { @@ -107,22 +107,20 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { } } } - + t.Logf("Retrieved %d short selling positions for code 7203", len(positions)) }) t.Run("GetShortSellingPositions_ByDisclosedDate", func(t *testing.T) { // 最近の金曜日の全銘柄空売り残高報告を取得 disclosedDate := getRecentFriday() - + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByDisclosedDate(context.Background(), disclosedDate) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - // データがない可能性もある - t.Logf("No positions data for date %s: %v", disclosedDate, err) - return + t.Fatalf("Failed to get positions for date %s: %v", disclosedDate, err) } if len(positions) == 0 { @@ -138,21 +136,21 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { break // 最初の10件のみ確認 } } - + // 銘柄別の集計 codeCount := make(map[string]int) sellerCount := make(map[string]int) - + for _, position := range positions { codeCount[position.Code]++ sellerCount[position.SSName]++ } - + t.Logf("Disclosed date %s summary:", disclosedDate) t.Logf(" Total positions: %d", len(positions)) t.Logf(" Unique codes: %d", len(codeCount)) t.Logf(" Unique sellers: %d", len(sellerCount)) - + // 最も多く報告している空売り者 maxCount := 0 topSeller := "" @@ -185,7 +183,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { increases := 0 decreases := 0 noChanges := 0 - + for _, position := range positions { if position.IsIncrease() { increases++ @@ -195,19 +193,19 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { noChanges++ } } - + t.Logf("Position change analysis for code 7203:") t.Logf(" Increases: %d", increases) t.Logf(" Decreases: %d", decreases) t.Logf(" No changes: %d", noChanges) - + // 大きな変化があったポジション t.Logf("Significant position changes:") for i, position := range positions { if i >= 5 { break } - + changeRatio := position.GetPositionChangeRatio() if abs(changeRatio) > 10 { // 10%以上の変化 direction := "increased" @@ -226,7 +224,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { // 過去1ヶ月の期間でトヨタ自動車の空売り残高を取得 to := time.Now().Format("2006-01-02") from := time.Now().AddDate(0, -1, 0).Format("2006-01-02") - + positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCodeAndDateRange(context.Background(), "7203", from, to) if err != nil { if isSubscriptionLimited(err) { @@ -240,7 +238,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { } t.Logf("Retrieved %d positions for period %s to %s", len(positions), from, to) - + // 期間内の日付確認 for _, position := range positions { if position.DiscDate < from || position.DiscDate > to { @@ -248,7 +246,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { position.DiscDate, from, to) } } - + // 時系列トレンド if len(positions) > 1 { t.Logf("Monthly trend analysis:") @@ -257,7 +255,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { if i >= 5 { break } - + currentRatio := position.ShrtPosToSO if i > 0 { change := currentRatio - prevRatio @@ -289,7 +287,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { below1Percent := 0 oneToFivePercent := 0 aboveFivePercent := 0 - + for _, position := range positions { ratio := position.ShrtPosToSO if ratio < 1.0 { @@ -300,12 +298,12 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { aboveFivePercent++ } } - + t.Logf("Position threshold analysis:") t.Logf(" Below 1%%: %d positions", below1Percent) t.Logf(" 1%% to 5%%: %d positions", oneToFivePercent) t.Logf(" Above 5%%: %d positions", aboveFivePercent) - + // 最大ポジション maxRatio := 0.0 maxSeller := "" @@ -315,7 +313,7 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { maxSeller = position.SSName } } - + if maxSeller != "" { t.Logf("Largest position: %s with %.2f%%", maxSeller, maxRatio) } @@ -323,13 +321,13 @@ func TestShortSellingPositionsEndpoint(t *testing.T) { t.Run("GetShortSellingPositions_ErrorHandling", func(t *testing.T) { // エラーケースのテスト - + // 存在しない銘柄コード positions, err := jq.ShortSellingPositions.GetShortSellingPositionsByCode(context.Background(), "99999") if err == nil && len(positions) > 0 { t.Error("Expected error or empty result for invalid code") } - + // 無効な日付 positions, err = jq.ShortSellingPositions.GetShortSellingPositionsByDisclosedDate(context.Background(), "invalid-date") if err == nil && len(positions) > 0 { @@ -356,4 +354,4 @@ func getRecentFriday() string { // さらに1週間前にする(当週のデータは利用できない可能性があるため) now = now.AddDate(0, 0, -7) return now.Format("2006-01-02") -} \ No newline at end of file +} diff --git a/test/e2e/short_selling_test.go b/test/e2e/short_selling_test.go index 28ac82b..6aebc77 100644 --- a/test/e2e/short_selling_test.go +++ b/test/e2e/short_selling_test.go @@ -13,7 +13,7 @@ func TestShortSellingEndpoint(t *testing.T) { t.Run("GetShortSelling_ByDate", func(t *testing.T) { // 最近の営業日の業種別空売り比率を取得 date := getTestDate() - + shorts, err := jq.ShortSelling.GetShortSellingByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { @@ -42,7 +42,7 @@ func TestShortSellingEndpoint(t *testing.T) { t.Errorf("ShortSelling[%d]: Date = %v, want %v", i, short.Date, expectedDate) } } - + if short.S33 == "" { t.Errorf("ShortSelling[%d]: Sector33Code is empty", i) } else { @@ -51,7 +51,7 @@ func TestShortSellingEndpoint(t *testing.T) { t.Errorf("ShortSelling[%d]: Sector33Code length = %d, want 4", i, len(short.S33)) } } - + // 売買代金の検証(負の値は通常ありえない) if short.SellExShortVa < 0 { t.Errorf("ShortSelling[%d]: SellingExcludingShortSellingTurnoverValue = %v, want >= 0", @@ -65,21 +65,21 @@ func TestShortSellingEndpoint(t *testing.T) { t.Errorf("ShortSelling[%d]: ShortSellingWithoutRestrictionsTurnoverValue = %v, want >= 0", i, short.ShrtNoResVa) } - + // 比率の計算と検証 totalTurnover := short.SellExShortVa + short.ShrtWithResVa + short.ShrtNoResVa - + if totalTurnover > 0 { shortSellingRatio := (short.ShrtWithResVa + short.ShrtNoResVa) / totalTurnover * 100 - + // 空売り比率が異常でないかチェック(通常0-50%程度) if shortSellingRatio > 100 { t.Errorf("ShortSelling[%d]: Short selling ratio too high: %.2f%%", i, shortSellingRatio) } - + // 最初の5件の詳細ログ if i < 5 { t.Logf("ShortSelling[%d]: Sector=%s, Date=%s", @@ -92,14 +92,14 @@ func TestShortSellingEndpoint(t *testing.T) { } } } - + t.Logf("Retrieved %d short selling records for date %s", len(shorts), date) }) t.Run("GetShortSellingBySector", func(t *testing.T) { // 特定業種(輸送用機器:3050)の空売り比率データを取得 sectorCode := "3050" - + shorts, err := jq.ShortSelling.GetShortSellingBySector(context.Background(), sectorCode) if err != nil { if isSubscriptionLimited(err) { @@ -124,9 +124,9 @@ func TestShortSellingEndpoint(t *testing.T) { } } } - + t.Logf("Retrieved %d short selling records for sector %s", len(shorts), sectorCode) - + // 時系列トレンド分析 if len(shorts) > 1 { t.Logf("Time series analysis for sector %s:", sectorCode) @@ -135,12 +135,12 @@ func TestShortSellingEndpoint(t *testing.T) { totalTurnover := short.SellExShortVa + short.ShrtWithResVa + short.ShrtNoResVa - + if totalTurnover > 0 { shortSellingRatio := (short.ShrtWithResVa + short.ShrtNoResVa) / totalTurnover * 100 - - t.Logf(" %s: %.2f%% short selling ratio (turnover: %.0f)", + + t.Logf(" %s: %.2f%% short selling ratio (turnover: %.0f)", short.Date, shortSellingRatio, totalTurnover) } } @@ -150,7 +150,7 @@ func TestShortSellingEndpoint(t *testing.T) { t.Run("GetShortSelling_SectorAnalysis", func(t *testing.T) { // 最新日の全業種の空売り比率分析 date := getTestDate() - + shorts, err := jq.ShortSelling.GetShortSellingByDate(context.Background(), date) if err != nil { if isSubscriptionLimited(err) { @@ -169,18 +169,18 @@ func TestShortSellingEndpoint(t *testing.T) { Ratio float64 Turnover float64 } - + var sectorRatios []SectorRatio - + for _, short := range shorts { totalTurnover := short.SellExShortVa + short.ShrtWithResVa + short.ShrtNoResVa - + if totalTurnover > 0 { shortSellingRatio := (short.ShrtWithResVa + short.ShrtNoResVa) / totalTurnover * 100 - + sectorRatios = append(sectorRatios, SectorRatio{ SectorCode: short.S33, Ratio: shortSellingRatio, @@ -188,7 +188,7 @@ func TestShortSellingEndpoint(t *testing.T) { }) } } - + // 上位10業種の空売り比率 t.Logf("Top 10 sectors by short selling ratio on %s:", date) count := 0 @@ -200,13 +200,13 @@ func TestShortSellingEndpoint(t *testing.T) { sector.SectorCode, sector.Ratio, sector.Turnover/1000000) count++ } - + // 統計情報 if len(sectorRatios) > 0 { var totalRatio, minRatio, maxRatio float64 minRatio = sectorRatios[0].Ratio maxRatio = sectorRatios[0].Ratio - + for _, sector := range sectorRatios { totalRatio += sector.Ratio if sector.Ratio < minRatio { @@ -216,7 +216,7 @@ func TestShortSellingEndpoint(t *testing.T) { maxRatio = sector.Ratio } } - + avgRatio := totalRatio / float64(len(sectorRatios)) t.Logf("Short selling ratio statistics:") t.Logf(" Average: %.2f%%", avgRatio) @@ -229,8 +229,8 @@ func TestShortSellingEndpoint(t *testing.T) { t.Run("GetShortSelling_MultiSector", func(t *testing.T) { // 複数の主要業種の比較 majorSectors := []string{"0050", "1050", "2050", "3050", "4050"} // 主要業種コード - sectorData := make(map[string][]float64) // セクター -> 直近の空売り比率リスト - + sectorData := make(map[string][]float64) // セクター -> 直近の空売り比率リスト + for _, sectorCode := range majorSectors { shorts, err := jq.ShortSelling.GetShortSellingBySector(context.Background(), sectorCode) if err != nil { @@ -239,11 +239,11 @@ func TestShortSellingEndpoint(t *testing.T) { } continue } - + if len(shorts) == 0 { continue } - + // 直近5日分の空売り比率を計算 ratios := make([]float64, 0, 5) for i := 0; i < 5 && i < len(shorts); i++ { @@ -251,19 +251,19 @@ func TestShortSellingEndpoint(t *testing.T) { totalTurnover := short.SellExShortVa + short.ShrtWithResVa + short.ShrtNoResVa - + if totalTurnover > 0 { ratio := (short.ShrtWithResVa + short.ShrtNoResVa) / totalTurnover * 100 ratios = append(ratios, ratio) } } - + if len(ratios) > 0 { sectorData[sectorCode] = ratios } } - + // 業種間比較 t.Logf("Major sectors comparison (recent 5 days avg):") for sectorCode, ratios := range sectorData { @@ -280,13 +280,13 @@ func TestShortSellingEndpoint(t *testing.T) { t.Run("GetShortSelling_ErrorHandling", func(t *testing.T) { // エラーケースのテスト - + // 存在しない業種コード(0000は無効) shorts, err := jq.ShortSelling.GetShortSellingBySector(context.Background(), "0000") if err == nil && len(shorts) > 0 { t.Error("Expected error or empty result for invalid sector code") } - + // 未来の日付 futureDate := "2030-01-01" shorts, err = jq.ShortSelling.GetShortSellingByDate(context.Background(), futureDate) @@ -294,4 +294,4 @@ func TestShortSellingEndpoint(t *testing.T) { t.Error("Expected error or empty result for future date") } }) -} \ No newline at end of file +} diff --git a/test/e2e/statements_test.go b/test/e2e/statements_test.go index 7a23f31..2ef3c99 100644 --- a/test/e2e/statements_test.go +++ b/test/e2e/statements_test.go @@ -6,6 +6,8 @@ package e2e import ( "context" "testing" + + "github.com/utahta/jquants" ) // TestStatementsEndpoint は/fins/statementsエンドポイントの完全なテスト @@ -26,7 +28,7 @@ func TestStatementsEndpoint(t *testing.T) { // 最新の財務諸表を詳細に検証 latest := statements[0] - + // 基本情報の検証 if latest.Code != "7203" && latest.Code != "72030" { t.Errorf("LocalCode = %v, want 7203 or 72030", latest.Code) @@ -65,7 +67,7 @@ func TestStatementsEndpoint(t *testing.T) { if latest.DiscNo == "" { t.Error("DisclosureNumber is empty") } - + // 書類・期間情報の検証 if latest.DocType == "" { t.Error("TypeOfDocument is empty") @@ -111,12 +113,12 @@ func TestStatementsEndpoint(t *testing.T) { t.Errorf("CurrentFiscalYearEndDate format invalid = %v, want YYYY-MM-DD", latest.CurFYEn) } } - + // 書類種別の検証(会計基準は実際の構造体にはない) if latest.DocType == "" { t.Error("TypeOfDocument is empty") } - + // 財務データの検証(nilチェックと値の妥当性確認) validateFinancialValue(t, "NetSales", latest.Sales) validateFinancialValue(t, "OperatingProfit", latest.OP) @@ -128,13 +130,13 @@ func TestStatementsEndpoint(t *testing.T) { validateFinancialValue(t, "Equity", latest.Eq) validateFinancialValue(t, "EquityToAssetRatio", latest.EqAR) validateFinancialValue(t, "BookValuePerShare", latest.BPS) - + // キャッシュフロー情報の検証 validateFinancialValue(t, "CashFlowsFromOperatingActivities", latest.CFO) validateFinancialValue(t, "CashFlowsFromInvestingActivities", latest.CFI) validateFinancialValue(t, "CashFlowsFromFinancingActivities", latest.CFF) validateFinancialValue(t, "CashAndEquivalents", latest.CashEq) - + // 配当情報の検証 validateFinancialValue(t, "ResultDividendPerShareAnnual", latest.DivAnn) validateFinancialValue(t, "ResultDividendPerShare1stQuarter", latest.Div1Q) @@ -142,7 +144,7 @@ func TestStatementsEndpoint(t *testing.T) { validateFinancialValue(t, "ResultDividendPerShare3rdQuarter", latest.Div3Q) validateFinancialValue(t, "ResultDividendPerShareFiscalYearEnd", latest.DivFY) validateFinancialValue(t, "ResultPayoutRatioAnnual", latest.PayoutRatioAn) - + // 新規追加フィールド: REIT関連と配当総額 validateFinancialValue(t, "DistributionsPerUnitREIT", latest.DivUnit) validateFinancialValue(t, "ResultTotalDividendPaidAnnual", latest.DivTotalAnn) @@ -158,7 +160,7 @@ func TestStatementsEndpoint(t *testing.T) { // 新規追加フィールド: 予想REIT関連と配当総額 validateFinancialValue(t, "ForecastDistributionsPerUnitREIT", latest.FDivUnit) validateFinancialValue(t, "ForecastTotalDividendPaidAnnual", latest.FDivTotalAnn) - + // 予想財務データの検証 validateFinancialValue(t, "ForecastNetSales", latest.FSales) validateFinancialValue(t, "ForecastOperatingProfit", latest.FOP) @@ -172,7 +174,7 @@ func TestStatementsEndpoint(t *testing.T) { validateFinancialValue(t, "ForecastOrdinaryProfit2ndQuarter", latest.FOdP2Q) validateFinancialValue(t, "ForecastProfit2ndQuarter", latest.FNP2Q) validateFinancialValue(t, "ForecastEarningsPerShare2ndQuarter", latest.FEPS2Q) - + // 翌期予想配当 validateFinancialValue(t, "NextYearForecastDividendPerShare1stQuarter", latest.NxFDiv1Q) validateFinancialValue(t, "NextYearForecastDividendPerShare2ndQuarter", latest.NxFDiv2Q) @@ -195,7 +197,7 @@ func TestStatementsEndpoint(t *testing.T) { validateFinancialValue(t, "NextYearForecastOrdinaryProfit", latest.NxFOdP) validateFinancialValue(t, "NextYearForecastProfit", latest.NxFNp) validateFinancialValue(t, "NextYearForecastEarningsPerShare", latest.NxFEPS) - + // 修正情報の検証(string型フィールド) t.Logf("MaterialChangesInSubsidiaries: %v", latest.MatChgSub) t.Logf("SignificantChangesInTheScopeOfConsolidation: %v", latest.SigChgInC) @@ -216,7 +218,7 @@ func TestStatementsEndpoint(t *testing.T) { if latest.AvgSh != nil { t.Logf("AverageNumberOfShares: %d", *latest.AvgSh) } - + // 単体財務データの検証 validateFinancialValue(t, "NonConsolidatedNetSales", latest.NCSales) validateFinancialValue(t, "NonConsolidatedOperatingProfit", latest.NCOP) @@ -255,7 +257,7 @@ func TestStatementsEndpoint(t *testing.T) { validateFinancialValue(t, "NextYearForecastNonConsolidatedOrdinaryProfit", latest.NxFNCOdP) validateFinancialValue(t, "NextYearForecastNonConsolidatedProfit", latest.NxFNCNP) validateFinancialValue(t, "NextYearForecastNonConsolidatedEarningsPerShare", latest.NxFNCEPS) - + t.Logf("Successfully validated all fields for statement: %s", latest.DiscDate) }) @@ -274,12 +276,12 @@ func TestStatementsEndpoint(t *testing.T) { } t.Logf("Retrieved %d statements", len(statements)) - + // 複数の決算期のデータが取得できているかを確認 if len(statements) >= 2 { first := statements[0] second := statements[1] - + // 決算期が異なることを確認 if first.CurFYEn == second.CurFYEn { t.Logf("Warning: Multiple statements with same fiscal year end date") @@ -291,44 +293,39 @@ func TestStatementsEndpoint(t *testing.T) { }) t.Run("GetStatementsByDate", func(t *testing.T) { - // 特定日の財務諸表を取得(過去の営業日を使用) - date := getTestDate() - - // GetStatementsByDateメソッドを使用 - statements, err := jq.Statements.GetStatementsByDate(context.Background(), date) - if err != nil { - if isSubscriptionLimited(err) { - t.Skip("Skipping due to subscription limitation") - } - // 指定日にデータがない可能性もある - t.Logf("No statements data for date %s: %v", date, err) - return + // 開示は毎営業日あるとは限らないため、開示がある営業日を直近から探す + var statements []jquants.Statement + date := findPopulatedTestDate(t, 5, func(d string) (int, error) { + var err error + statements, err = jq.Statements.GetStatementsByDate(context.Background(), d) + return len(statements), err + }) + if date == "" { + t.Skip("No statements found on recent trading days") } - if len(statements) > 0 { - t.Logf("Found %d statements for date %s", len(statements), date) - - // 各財務諸表の基本検証 - for i, stmt := range statements { - if i >= 5 { - break // 最初の5件のみ詳細検証 - } - - if stmt.Code == "" { - t.Errorf("Statement[%d]: Code is empty", i) - } else { - // Codeは5桁 - if len(stmt.Code) != 5 { - t.Errorf("Statement[%d]: Code length = %d, want 5", i, len(stmt.Code)) - } - } - // DiscDateの検証(APIはYYYY-MM-DD形式で返す) - expectedDate := getTestDateFormatted() - if stmt.DiscDate != expectedDate { - t.Errorf("Statement[%d]: DiscDate = %v, want %v", i, stmt.DiscDate, expectedDate) + t.Logf("Found %d statements for date %s", len(statements), date) + + // 各財務諸表の基本検証 + for i, stmt := range statements { + if i >= 5 { + break // 最初の5件のみ詳細検証 + } + + if stmt.Code == "" { + t.Errorf("Statement[%d]: Code is empty", i) + } else { + // Codeは5桁 + if len(stmt.Code) != 5 { + t.Errorf("Statement[%d]: Code length = %d, want 5", i, len(stmt.Code)) } - t.Logf("Statement[%d]: %s - %s", i, stmt.Code, stmt.DocType) } + // DiscDateの検証(APIはYYYY-MM-DD形式で返す) + expectedDate := formatDate(date) + if stmt.DiscDate != expectedDate { + t.Errorf("Statement[%d]: DiscDate = %v, want %v", i, stmt.DiscDate, expectedDate) + } + t.Logf("Statement[%d]: %s - %s", i, stmt.Code, stmt.DocType) } }) } @@ -346,4 +343,4 @@ func validateFinancialValue(t *testing.T, fieldName string, value *float64) { // nilは許容される(すべての企業がすべてのフィールドを持つわけではない) t.Logf("%s: nil", fieldName) } -} \ No newline at end of file +} diff --git a/test/e2e/topix_test.go b/test/e2e/topix_test.go index a29ead4..b42862f 100644 --- a/test/e2e/topix_test.go +++ b/test/e2e/topix_test.go @@ -156,8 +156,7 @@ func TestTOPIXEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get TOPIX data for single day: %v", err) - return + t.Fatalf("Failed to get TOPIX data for single day: %v", err) } if resp != nil && len(resp.Data) > 0 { diff --git a/test/e2e/trades_spec_test.go b/test/e2e/trades_spec_test.go index 2e352eb..0411d1f 100644 --- a/test/e2e/trades_spec_test.go +++ b/test/e2e/trades_spec_test.go @@ -5,6 +5,7 @@ package e2e import ( "context" + "strings" "testing" "time" @@ -14,19 +15,34 @@ import ( // TestTradesSpecEndpoint は/equities/investor-typesエンドポイントの完全なテスト func TestTradesSpecEndpoint(t *testing.T) { t.Run("GetTradesSpec_ByDateRange", func(t *testing.T) { - // 最近の営業日の投資部門別売買状況を取得 - date := getTestDate() - - trades, err := jq.TradesSpec.GetTradesSpecByDateRange(context.Background(), date, date) + // 週次データのため、直近30日の範囲から公表済みデータを特定し、 + // その公表日で単日クエリを検証する(from/toは公表日でフィルタされる) + rangeTrades, err := jq.TradesSpec.GetTradesSpecByDateRange(context.Background(), getTestDateDaysAgo(30), getTestDate()) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } t.Fatalf("Failed to get trades spec: %v", err) } + if len(rangeTrades) == 0 { + t.Skip("No trades spec data in the last 30 days") + } + // 最新の公表日を単日クエリの対象にする + latestPub := "" + for _, tr := range rangeTrades { + if tr.PubDate > latestPub { + latestPub = tr.PubDate + } + } + date := strings.ReplaceAll(latestPub, "-", "") + + trades, err := jq.TradesSpec.GetTradesSpecByDateRange(context.Background(), date, date) + if err != nil { + t.Fatalf("Failed to get trades spec for %s: %v", date, err) + } if len(trades) == 0 { - t.Skip("No trades spec data available") + t.Fatalf("Expected trades spec data for populated date %s, got none", date) } // 各投資部門別売買データを詳細に検証 @@ -118,29 +134,27 @@ func TestTradesSpecEndpoint(t *testing.T) { } }) - t.Run("GetTradesSpecBySection_All", func(t *testing.T) { - // 全市場の投資部門別売買状況を取得 - trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), "All") + t.Run("GetTradesSpecBySection_TokyoNagoya", func(t *testing.T) { + // 東証および名証(最も広い集計区分)の投資部門別売買状況を取得 + trades, err := jq.TradesSpec.GetTradesSpecBySection(context.Background(), jquants.SectionTokyoNagoya) if err != nil { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get trades spec for All: %v", err) - return + t.Fatalf("Failed to get trades spec for TokyoNagoya: %v", err) } if len(trades) == 0 { - t.Skip("No trades spec data available for All") + t.Skip("No trades spec data available for TokyoNagoya") } - // 全市場データの検証 for i, trade := range trades { - if trade.Section != "All" { - t.Errorf("Trade[%d]: Section = %v, want All", i, trade.Section) + if trade.Section != jquants.SectionTokyoNagoya { + t.Errorf("Trade[%d]: Section = %v, want %v", i, trade.Section, jquants.SectionTokyoNagoya) } } - t.Logf("Retrieved %d All market trades spec records", len(trades)) + t.Logf("Retrieved %d TokyoNagoya trades spec records", len(trades)) }) t.Run("GetTradesSpec_MultipleMarkets", func(t *testing.T) { @@ -154,8 +168,7 @@ func TestTradesSpecEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get trades spec for %s: %v", market, err) - continue + t.Fatalf("Failed to get trades spec for %s: %v", market, err) } if len(trades) > 0 { diff --git a/test/e2e/trading_calendar_test.go b/test/e2e/trading_calendar_test.go index d8bf346..ffee507 100644 --- a/test/e2e/trading_calendar_test.go +++ b/test/e2e/trading_calendar_test.go @@ -93,8 +93,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { if strings.Contains(err.Error(), "status=502") { t.Skipf("Skipping due to temporary server error: %v", err) } - t.Logf("Failed to get trading calendar for historical period: %v", err) - return + t.Fatalf("Failed to get trading calendar for historical period: %v", err) } if len(calendar) == 0 { @@ -246,8 +245,7 @@ func TestTradingCalendarEndpoint(t *testing.T) { if strings.Contains(err.Error(), "status=502") { t.Skipf("Skipping due to temporary server error: %v", err) } - t.Logf("Failed to get calendar for single date: %v", err) - return + t.Fatalf("Failed to get calendar for single date: %v", err) } if len(calendar) == 0 { diff --git a/test/e2e/weekly_margin_interest_test.go b/test/e2e/weekly_margin_interest_test.go index d82eab7..b05db47 100644 --- a/test/e2e/weekly_margin_interest_test.go +++ b/test/e2e/weekly_margin_interest_test.go @@ -130,8 +130,7 @@ func TestWeeklyMarginInterestEndpoint(t *testing.T) { if isSubscriptionLimited(err) { t.Skip("Skipping due to subscription limitation") } - t.Logf("Failed to get weekly margin interest by date: %v", err) - return + t.Fatalf("Failed to get weekly margin interest by date: %v", err) } if resp == nil || len(resp.Data) == 0 {