forked from grailbio/go-netdicom
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathe2e_test.go
492 lines (444 loc) · 13.6 KB
/
e2e_test.go
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package netdicom
import (
"bytes"
"context"
"encoding/binary"
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/antibios/dicom"
"github.com/antibios/dicom/pkg/tag"
"github.com/antibios/dicom/pkg/uid"
"github.com/antibios/go-netdicom/dimse"
"github.com/antibios/go-netdicom/sopclass"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var provider *ServiceProvider
var cstoreData []byte // data received by the cstore handler
var cstoreStatus = dimse.Success // status returned by the cstore handler
var nEchoRequests int
var once sync.Once
func TestMain(m *testing.M) {
flag.Parse()
var err error
provider, err = NewServiceProvider(ServiceProviderParams{
CEcho: onCEchoRequest,
CStore: onCStoreRequest,
CFind: onCFindRequest,
CGet: onCGetRequest,
}, ":0")
if err != nil {
panic(err)
}
go provider.Run()
os.Exit(m.Run())
}
func onCEchoRequest(connState ConnectionState) dimse.Status {
nEchoRequests++
return dimse.Success
}
func onCStoreRequest(
connState ConnectionState,
transferSyntaxUID string,
sopClassUID string,
sopInstanceUID string,
callingAETitle string,
calledAETitle string,
data []byte) dimse.Status {
log.Printf("Start C-STORE handler, transfersyntax=%s, sopclass=%s, sopinstance=%s",
uid.UIDString(transferSyntaxUID),
uid.UIDString(sopClassUID),
uid.UIDString(sopInstanceUID))
/* e := dicomio.NewBytesEncoder(nil, dicomio.UnknownVR)
dicom.WriteFileHeader(e, */
b := bytes.Buffer{}
e := dicom.NewWriter(&b, dicom.SkipVRVerification())
e.SetTransferSyntax(binary.LittleEndian, true)
for _, elem := range []*dicom.Element{
dicom.MustNewElement(tag.TransferSyntaxUID, transferSyntaxUID),
dicom.MustNewElement(tag.MediaStorageSOPClassUID, sopClassUID),
dicom.MustNewElement(tag.MediaStorageSOPInstanceUID, sopInstanceUID),
} {
e.WriteElement(elem)
}
e.WriteBytes(data)
cstoreData = data
log.Printf("Received C-STORE request, %d bytes", len(cstoreData))
return cstoreStatus
}
func onCFindRequest(
connState ConnectionState,
transferSyntaxUID string,
sopClassUID string,
filters []*dicom.Element,
ch chan CFindResult) {
log.Printf("Received cfind request")
found := 0
for _, elem := range filters {
log.Printf("Filter %v", elem)
if elem.Tag == tag.QueryRetrieveLevel {
if elem.String() != "PATIENT" {
log.Panicf("Wrong QR level: %v", elem)
}
found++
}
if elem.Tag == tag.PatientName {
if elem.String() != "foohah" {
log.Panicf("Wrong patient name: %v", elem)
}
found++
}
}
if found != 2 {
log.Panicf("Didn't find expected filters: %v", filters)
}
ch <- CFindResult{
Elements: []*dicom.Element{dicom.MustNewElement(tag.PatientName, "johndoe")},
}
ch <- CFindResult{
Elements: []*dicom.Element{dicom.MustNewElement(tag.PatientName, "johndoe2")},
}
close(ch)
}
func onCGetRequest(
connState ConnectionState,
transferSyntaxUID string,
sopClassUID string,
filters []*dicom.Element,
ch chan CMoveResult) {
log.Printf("Received cget request")
path := "testdata/reportsi.dcm"
dataset := mustReadDICOMFile(path)
ch <- CMoveResult{
Remaining: -1,
Path: path,
DataSet: dataset,
}
close(ch)
}
// Test compare elements a and b with i being an count of the element in the DICOM header.
func compareElements(t *testing.T, a, b dicom.Element, i int) bool {
if a.Tag != b.Tag {
t.Errorf("%dth Tag element mismatch: %v <-> %v", i, a.Tag, b.Tag)
}
if a.RawValueRepresentation != b.RawValueRepresentation {
t.Errorf("%dth Tag Representation mismatch: %v <-> %v", i, b.RawValueRepresentation, b.RawValueRepresentation)
}
if a.RawValueRepresentation == "SQ" {
as := a.Value.GetValue().([]*dicom.SequenceItemValue)
bs := b.Value.GetValue().([]*dicom.SequenceItemValue)
if len(as) != len(bs) {
t.Errorf("Sequence length incorrect %v <-> %v", as, bs)
}
for j, _ := range as {
for n, _ := range as[j].GetValue().([]*dicom.Element) {
compareElements(t, *as[j].GetValue().([]*dicom.Element)[n], *bs[j].GetValue().([]*dicom.Element)[n], n)
}
}
//Now check Value
} else if !reflect.DeepEqual(a.Value.GetValue(), b.Value.GetValue()) {
t.Errorf("%dth Value element mismatch: %v <-> %v", i, a.Value.GetValue(), b.Value.GetValue())
}
return true
}
// Check that two datasets, "in" and "out" are the same, except for metadata
// elements.
func checkFileBodiesEqual(t *testing.T, in, out *dicom.Dataset) {
// DCMTK arbitrarily changes the sequences and items to use
// undefined-length encoding, so ignore such diffs.
/* var normalize = func(s string) string {
s = strings.Replace(s, "NA u", "NA ", -1)
s = strings.Replace(s, "SQ u", "SQ ", -1)
return s
} */
var removeMetaElems = func(f *dicom.Dataset) []*dicom.Element {
var elems []*dicom.Element
for _, elem := range f.Elements {
if elem.Tag.Group != tag.MetadataGroup {
elems = append(elems, elem)
}
}
return elems
}
inElems := removeMetaElems(in)
outElems := removeMetaElems(out)
assert.Equal(t, len(inElems), len(outElems))
for i := 0; i < len(inElems); i++ {
/* ins := normalize(inElems[i].String())
outs := normalize(outElems[i].String())
if ins != outs {
t.Errorf("%dth element mismatch: %v <-> %v", i, ins, outs)
}
*/
//Tag
compareElements(t, *inElems[i], *outElems[i], i)
}
}
// Get the dataset received by the cstore handler.
func getCStoreData() (*dicom.Dataset, error) {
if len(cstoreData) == 0 {
return nil, errors.New("Did not receive C-STORE data")
}
//f, err := dicom.ReadDataSetInBytes(cstoreData, dicom.ReadOptions{})
//reader := bytes.NewReader(cstoreData)
//f, err := dicom.ParseUntilEOF(reader, nil, dicom.SkipMetadataReadOnNewParserInit())
f, err := dicom.ReadDataSetInBytes(&cstoreData, dicom.SkipMetadataReadOnNewParserInit())
if err != nil {
return nil, err
}
return &f, nil
}
func mustReadDICOMFile(path string) *dicom.Dataset {
dataset, err := dicom.ParseFile(path, nil)
if err != nil {
log.Panic(err)
}
return &dataset
}
func mustNewServiceUser(t *testing.T, sopClasses []string) *ServiceUser {
su, err := NewServiceUser(ServiceUserParams{SOPClasses: sopClasses})
require.NoError(t, err)
log.Printf("Connecting to %v", provider.ListenAddr().String())
su.Connect(provider.ListenAddr().String())
return su
}
func TestStore(t *testing.T) {
dataset := mustReadDICOMFile("testdata/IM-0001-0003.dcm")
su := mustNewServiceUser(t, sopclass.StorageClasses)
defer su.Release()
err := su.CStore(dataset)
if err != nil {
log.Panic(err)
}
log.Printf("Store done!!")
out, err := getCStoreData()
if err != nil {
log.Panic(err)
}
checkFileBodiesEqual(t, dataset, out)
}
// Arrange so that the cstore server returns an error. The client should detect
// that.
func TestStoreFailure0(t *testing.T) {
dataset := mustReadDICOMFile("testdata/IM-0001-0003.dcm")
cstoreStatus = dimse.Status{Status: dimse.StatusNotAuthorized, ErrorComment: "Foohah"}
defer func() { cstoreStatus = dimse.Success }()
su := mustNewServiceUser(t, sopclass.StorageClasses)
defer su.Release()
err := su.CStore(dataset)
if err == nil || strings.Index(err.Error(), "Foohah") < 0 {
log.Panic(err)
}
}
func getProviderPort() string {
match := regexp.MustCompile("(\\d+)$").FindStringSubmatch(provider.ListenAddr().String())
return match[1]
}
func TestDCMTKEcho(t *testing.T) {
echoscuPath, err := exec.LookPath("echoscu")
if err != nil {
t.Skip("echoscu not found.")
return
}
cstoreData = nil
cmd := exec.Command(echoscuPath, "localhost", getProviderPort())
require.NoError(t, cmd.Run())
}
func waitForDicomSuccess() bool {
// Set a timeout of 3 seconds
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
go func() {
for {
// Test your condition here
// ...
if cstoreStatus == dimse.Success {
cancel() // Cancel the context if the condition becomes true
return
}
select {
case <-ctx.Done():
fmt.Println("cstoreStatus not met within timeout: ", cstoreStatus)
return
case <-time.After(100 * time.Millisecond):
// Do nothing, loop continues checking the condition
}
}
}()
// Wait for the goroutine to finish
<-ctx.Done()
if cstoreStatus == dimse.Success {
fmt.Println("Condition became true within timeout")
return true
}
return false
}
// Test using "storescu" command from dcmtk.
func TestDCMTKCStore(t *testing.T) {
storescuPath, err := exec.LookPath("storescu")
if err != nil {
t.Skip("storescu not found.")
return
}
cstoreData = nil
cmd := exec.Command(storescuPath, "localhost", getProviderPort(), "testdata/reportsi.dcm")
require.NoError(t, cmd.Run())
require.True(t, waitForDicomSuccess() == true, "No sucessful send")
require.True(t, len(cstoreData) > 0, "No data received")
ds, err := dicom.ReadDataSetInBytes(&cstoreData)
require.NoError(t, err)
expected := mustReadDICOMFile("testdata/reportsi.dcm")
checkFileBodiesEqual(t, expected, &ds)
}
// Test using "getscu" command from dcmtk.
func TestDCMTKCGet(t *testing.T) {
tempDir, err := os.MkdirTemp("", "")
require.NoError(t, err)
defer os.RemoveAll(tempDir)
getscuPath, err := exec.LookPath("getscu")
if err != nil {
t.Skip("getscu not found.")
return
}
log.Printf("PORT is %v %v", getProviderPort(), tempDir)
cmd := exec.Command(getscuPath, "localhost", getProviderPort(), "-od", tempDir, "-k", "0010,0020=foo" /*not used*/)
require.NoError(t, cmd.Run())
require.NoError(t, err)
files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Equal(t, len(files), 1)
t.Logf("Found C-GET file %v/%v", tempDir, files[0].Name())
expected := mustReadDICOMFile("testdata/reportsi.dcm")
ds, err := dicom.ParseFile(filepath.Join(tempDir, files[0].Name()), nil, nil)
//ds, err := dicom.ReadDataSetFromFile(filepath.Join(tempDir, files[0].Name()), dicom.ReadOptions{})
require.NoError(t, err)
checkFileBodiesEqual(t, expected, &ds)
}
type testFaultInjector struct {
connected bool
}
func (fi *testFaultInjector) onStateTransition(oldState stateType, event *stateEvent, action *stateAction, newState stateType) {
if newState == sta06 {
// sta06 is the "association ready" state.
fi.connected = true
}
}
func (fi *testFaultInjector) onSend(data []byte) faultInjectorAction {
if fi.connected {
log.Printf("Disconnecting!")
return faultInjectorDisconnect
}
return faultInjectorContinue
}
func (fi *testFaultInjector) String() string {
return "testFaultInjector"
}
// Similar to the previous test, but inject a network failure during send.
func TestStoreFailure1(t *testing.T) {
dataset := mustReadDICOMFile("testdata/IM-0001-0003.dcm")
SetUserFaultInjector(&testFaultInjector{})
defer SetUserFaultInjector(nil)
su := mustNewServiceUser(t, sopclass.StorageClasses)
defer su.Release()
err := su.CStore(dataset)
if err == nil || strings.Index(err.Error(), "Connection failed") < 0 {
log.Panic(err)
}
}
func TestEcho(t *testing.T) {
su := mustNewServiceUser(t, sopclass.VerificationClasses)
defer su.Release()
oldCount := nEchoRequests
if err := su.CEcho(); err != nil {
log.Panic(err)
}
if nEchoRequests != oldCount+1 {
log.Panic("C-ECHO handler did not run")
}
}
func TestFind(t *testing.T) {
su := mustNewServiceUser(t, sopclass.QRFindClasses)
defer su.Release()
filter := []*dicom.Element{
dicom.MustNewElement(tag.PatientName, "foohah"),
}
var namesFound []string
for result := range su.CFind(QRLevelPatient, filter) {
log.Printf("Got result: %v", result)
if result.Err != nil {
t.Error(result.Err)
continue
}
for _, elem := range result.Elements {
if elem.Tag != tag.PatientName {
t.Error(elem)
}
namesFound = append(namesFound, elem.Value.GetValue().(string))
}
}
if len(namesFound) != 2 || namesFound[0] != "johndoe" || namesFound[1] != "johndoe2" {
t.Error(namesFound)
}
}
func TestCGet(t *testing.T) {
su := mustNewServiceUser(t, sopclass.QRGetClasses)
defer su.Release()
filter := []*dicom.Element{
dicom.MustNewElement(tag.PatientName, "foohah"),
}
var cgetData []byte
err := su.CGet(QRLevelPatient, filter,
func(transferSyntaxUID, sopClassUID, sopInstanceUID string, data []byte) dimse.Status {
log.Printf("Got data: %v %v %v %d bytes", transferSyntaxUID, sopClassUID, sopInstanceUID, len(data))
require.True(t, len(cgetData) == 0, "Received multiple C-GET responses")
/* e := dicomio.NewBytesEncoder(nil, dicomio.UnknownVR)
dicom.WriteFileHeader(e, */
b := bytes.Buffer{}
e := dicom.NewWriter(&b, dicom.SkipVRVerification())
for _, elem := range []*dicom.Element{
dicom.MustNewElement(tag.TransferSyntaxUID, transferSyntaxUID),
dicom.MustNewElement(tag.MediaStorageSOPClassUID, sopClassUID),
dicom.MustNewElement(tag.MediaStorageSOPInstanceUID, sopInstanceUID),
} {
e.WriteElement(elem)
}
//e.WriteBytes(data)
cgetData = b.Bytes()
return dimse.Success
})
require.NoError(t, err)
require.True(t, len(cgetData) > 0, "No data received")
ds, err := dicom.ReadDataSetInBytes(&cgetData, nil)
require.NoError(t, err)
expected := mustReadDICOMFile("testdata/reportsi.dcm")
checkFileBodiesEqual(t, expected, &ds)
}
func TestReleaseWithoutConnect(t *testing.T) {
su, err := NewServiceUser(ServiceUserParams{
SOPClasses: sopclass.StorageClasses})
require.NoError(t, err)
su.Release()
}
func TestNonexistentServer(t *testing.T) {
su, err := NewServiceUser(ServiceUserParams{
SOPClasses: sopclass.StorageClasses})
require.NoError(t, err)
defer su.Release()
su.Connect(":99999")
err = su.CStore(mustReadDICOMFile("testdata/IM-0001-0003.dcm"))
if err == nil || !strings.Contains(err.Error(), "Connection failed") {
log.Panicf("Expect C-STORE to fail: %v", err)
}
}
// TODO(saito) Test that the state machine shuts down properly.