1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
|
namespace FundLab.Api.Tests
open System
open System.Diagnostics
open System.IO
open System.Text.Json
open System.Threading
open Xunit
open FundLab.Api
module NavDateProbeSupport =
let navPayloadJson (code: string) (observations: (string * string) list) =
let body =
observations
|> List.map (fun (date, nav) ->
sprintf
"{\"nav_date\":\"%s\",\"published_at\":null,\"nav\":\"%s\",\"accumulated_nav\":null,\"daily_return\":null}"
date
nav)
|> String.concat ","
sprintf
"{\"schema_version\":\"fund-lab.akshare.v1\",\"operation\":\"nav\",\"source\":\"akshare\",\"source_revision\":\"akshare-test/eastmoney\",\"collected_at\":\"2026-09-21T08:00:00Z\",\"instrument\":{\"code\":\"%s\"},\"observations\":[%s]}"
code
body
let collectorReturning (fetch: unit -> Result<string, string>) =
{ new IMarketDataCollector with
member _.Search(_, _) = Ok ""
member _.FetchNav(_, _) = fetch () }
let realAksharePython () =
let configured = Environment.GetEnvironmentVariable("FUND_LAB_AKSHARE_PYTHON")
if String.IsNullOrWhiteSpace configured then
None
elif File.Exists configured then
Some configured
else
let path = Environment.GetEnvironmentVariable("PATH") |> Option.ofObj |> Option.defaultValue ""
path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
|> Array.tryPick (fun directory ->
let candidate = Path.Combine(directory, configured)
if File.Exists candidate then Some candidate else None)
let repositoryRoot () =
let mutable directory = DirectoryInfo(AppContext.BaseDirectory)
while not (isNull directory)
&& not (File.Exists(Path.Combine(directory.FullName, "scripts", "probe_akshare_nav_dates.py"))) do
directory <- directory.Parent
if isNull directory then
failwith "could not locate scripts/probe_akshare_nav_dates.py from the test output directory"
else
directory.FullName
/// xUnit has no first-class runtime skip in 2.x, so this fact sets Skip during
/// discovery when the host has no reachable AKShare interpreter configured.
/// That keeps the live probe detectable ("skipped, not faked") instead of red.
type RealAkshareFactAttribute() =
inherit FactAttribute()
do
if (NavDateProbeSupport.realAksharePython ()).IsNone then
base.Skip <-
"set FUND_LAB_AKSHARE_PYTHON to a python interpreter with akshare installed to run the live probe"
[<Collection("postgres")>]
type NavDateProbeTests(fixture: PostgresFixture) =
let repository () = FundRepository(fixture.ConnectionString)
let stubSeriesProbe =
{ new INavSeriesProbe with
member _.RecentNavSeries(_, _, _) = Ok [] }
let appWithProbe (probe: INavDateProbe) =
App.createApplicationWithProbes (repository ()) { NavDates = probe; NavSeries = stubSeriesProbe }
[<Fact>]
member _.``probe parses, dedupes, sorts descending and truncates``() =
let payload =
NavDateProbeSupport.navPayloadJson
"000001"
[
"2026-09-16", "1.1205"
"2026-09-21", "1.1902"
"2026-09-16", "1.1205"
"2026-09-18", "1.1500"
"2026-09-17", "1.1180"
"2026-09-15", "1.1000"
"2026-09-11", "1.0900"
]
let probe = AkshareNavDateProbe(NavDateProbeSupport.collectorReturning (fun () -> Ok payload)) :> INavDateProbe
match probe.RecentNavDates("000001", 5, CancellationToken.None) with
| Ok dates ->
Assert.Equal<DateOnly list>(
[
DateOnly(2026, 9, 21)
DateOnly(2026, 9, 18)
DateOnly(2026, 9, 17)
DateOnly(2026, 9, 16)
DateOnly(2026, 9, 15)
],
dates
)
| Error failure -> failwithf "expected NAV dates, got %A" failure
[<Fact>]
member _.``probe memoises successful lookups per code``() =
let mutable calls = 0
let collector =
NavDateProbeSupport.collectorReturning (fun () ->
calls <- calls + 1
Ok(NavDateProbeSupport.navPayloadJson "000001" [ "2026-09-21", "1.1902" ]))
let probe = AkshareNavDateProbe(collector) :> INavDateProbe
let first = probe.RecentNavDates("000001", 5, CancellationToken.None)
let second = probe.RecentNavDates("000001", 5, CancellationToken.None)
Assert.Equal(Ok [ DateOnly(2026, 9, 21) ], first)
Assert.Equal(Ok [ DateOnly(2026, 9, 21) ], second)
Assert.Equal(1, calls)
[<Fact>]
member _.``probe rejects a malformed fund code without touching the collector``() =
let collector =
NavDateProbeSupport.collectorReturning (fun () -> failwith "collector should not be called")
let probe = AkshareNavDateProbe(collector) :> INavDateProbe
match probe.RecentNavDates("abc", 5, CancellationToken.None) with
| Error (InvalidMarketDataRequest message) -> Assert.Contains("six digits", message)
| other -> failwithf "expected InvalidMarketDataRequest, got %A" other
[<Fact>]
member _.``probe maps collector failures to an unavailable reason``() =
let collector =
NavDateProbeSupport.collectorReturning (fun () -> Error "AKShare is unreachable: connection timed out")
let probe = AkshareNavDateProbe(collector) :> INavDateProbe
match probe.RecentNavDates("000001", 5, CancellationToken.None) with
| Error (MarketDataCollectorUnavailable message) -> Assert.Contains("connection timed out", message)
| other -> failwithf "expected MarketDataCollectorUnavailable, got %A" other
[<Fact>]
member _.``probe maps malformed payloads to an invalid payload reason``() =
let probe =
AkshareNavDateProbe(NavDateProbeSupport.collectorReturning (fun () -> Ok "{not-json")) :> INavDateProbe
match probe.RecentNavDates("000001", 5, CancellationToken.None) with
| Error (InvalidMarketDataPayload _) -> ()
| other -> failwithf "expected InvalidMarketDataPayload, got %A" other
[<Fact>]
member _.``market nav-dates endpoint returns the probe dates``() =
let probe =
{ new INavDateProbe with
member _.RecentNavDates(code, limit, _) =
Assert.Equal("000001", code)
Assert.Equal(5, limit)
Ok [ DateOnly(2026, 9, 21); DateOnly(2026, 9, 18) ] }
let status, body =
PersistenceTestHelpers.invoke
(appWithProbe probe)
"GET"
"/api/market/nav-dates?code=000001"
[ "Authorization", "Bearer test-token" ]
""
Assert.Equal(200, status)
Assert.Contains("\"code\":\"000001\"", body)
Assert.Contains("\"dates\":[\"2026-09-21\",\"2026-09-18\"]", body)
[<Fact>]
member _.``market nav-dates endpoint answers 503 when the probe fails``() =
let probe =
{ new INavDateProbe with
member _.RecentNavDates(_, _, _) =
Error(MarketDataCollectorUnavailable "AKShare is unreachable: connection timed out") }
let status, body =
PersistenceTestHelpers.invoke
(appWithProbe probe)
"GET"
"/api/market/nav-dates?code=000001"
[ "Authorization", "Bearer test-token" ]
""
Assert.Equal(503, status)
Assert.Contains("MARKET_DATA_UNAVAILABLE", body)
Assert.Contains("connection timed out", body)
[<Fact>]
member _.``market nav-dates endpoint rejects a malformed code with 400``() =
let probe =
{ new INavDateProbe with
member _.RecentNavDates(_, _, _) =
Error(InvalidMarketDataRequest "fund code must contain exactly six digits") }
let status, body =
PersistenceTestHelpers.invoke
(appWithProbe probe)
"GET"
"/api/market/nav-dates?code=abc"
[ "Authorization", "Bearer test-token" ]
""
Assert.Equal(400, status)
Assert.Contains("INVALID_MARKET_DATA_REQUEST", body)
[<RealAkshareFact>]
member _.``live AKShare probe returns the five most recent NAV dates``() =
let python = (NavDateProbeSupport.realAksharePython ()).Value
let script = Path.Combine(NavDateProbeSupport.repositoryRoot (), "scripts", "probe_akshare_nav_dates.py")
let startInfo = ProcessStartInfo(python)
startInfo.ArgumentList.Add script
startInfo.ArgumentList.Add "--code"
startInfo.ArgumentList.Add "000001"
startInfo.ArgumentList.Add "--limit"
startInfo.ArgumentList.Add "5"
startInfo.RedirectStandardOutput <- true
startInfo.RedirectStandardError <- true
startInfo.UseShellExecute <- false
match Environment.GetEnvironmentVariable("FUND_LAB_AKSHARE_PYTHONPATH") with
| value when not (String.IsNullOrWhiteSpace value) -> startInfo.Environment["PYTHONPATH"] <- value
| _ -> ()
use probeProcess = Process.Start startInfo
let standardOutput = probeProcess.StandardOutput.ReadToEnd()
let standardError = probeProcess.StandardError.ReadToEnd()
probeProcess.WaitForExit 60000 |> ignore
Assert.True(probeProcess.ExitCode = 0, sprintf "probe exited with %d: %s" probeProcess.ExitCode standardError)
use document = JsonDocument.Parse standardOutput
let dates =
document.RootElement.GetProperty("dates").EnumerateArray()
|> Seq.map (fun element -> element.GetString())
|> Seq.toList
Assert.Equal(5, List.length dates)
Assert.Equal<string list>(List.sortDescending dates, dates)
|