forked from rhinoman/couchdb-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcouchdb_test.go
707 lines (649 loc) · 16.9 KB
/
couchdb_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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
package couchdb
import (
"bytes"
"encoding/json"
"github.com/twinj/uuid"
"io/ioutil"
"math/rand"
"strconv"
"testing"
"time"
)
var timeout = time.Duration(500 * time.Millisecond)
var unittestdb = "unittestdb"
var server = "127.0.0.1"
var numDbs = 1
var adminAuth = &BasicAuth{Username: "adminuser", Password: "password"}
type TestDocument struct {
Title string
Note string
}
type ViewResult struct {
Id string `json:"id"`
Key TestDocument `json:"key"`
}
type ViewResponse struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offset"`
Rows []ViewResult `json:"rows,omitempty"`
}
type MultiReadResponse struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offset"`
Rows []MultiReadRow `json:"rows"`
}
type MultiReadRow struct {
Id string `json:"id"`
Key string `json:"key"`
Doc TestDocument `json:"doc"`
}
type ListResult struct {
Id string `json:"id"`
Key TestDocument `json:"key"`
//Value string `json:"value"`
}
type ListResponse struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offset"`
Rows []ListResult `json:"rows,omitempty"`
}
type FindResponse struct {
Docs []TestDocument `json:"docs"`
}
type View struct {
Map string `json:"map"`
Reduce string `json:"reduce,omitempty"`
}
type DesignDocument struct {
Language string `json:"language"`
Views map[string]View `json:"views"`
Lists map[string]string `json:"lists"`
}
func getUuid() string {
theUuid := uuid.NewV4()
return uuid.Formatter(theUuid, uuid.FormatHex)
}
func getConnection(t *testing.T) *Connection {
conn, err := NewConnection(server, 5984, timeout)
if err != nil {
t.Logf("ERROR: %v", err)
t.Fail()
}
return conn
}
/*func getAuthConnection(t *testing.T) *Connection {
auth := Auth{Username: "adminuser", Password: "password"}
conn, err := NewConnection(server, 5984, timeout)
if err != nil {
t.Logf("ERROR: %v", err)
t.Fail()
}
return conn
}*/
func createTestDb(t *testing.T) string {
conn := getConnection(t)
dbName := unittestdb + strconv.Itoa(numDbs)
err := conn.CreateDB(dbName, adminAuth)
errorify(t, err)
numDbs += 1
return dbName
}
func deleteTestDb(t *testing.T, dbName string) {
conn := getConnection(t)
err := conn.DeleteDB(dbName, adminAuth)
errorify(t, err)
}
func genRandomText(n int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func createLotsDocs(t *testing.T, db *Database) {
for i := 0; i < 10; i++ {
id := getUuid()
note := "purple"
if i%2 == 0 {
note = "magenta"
}
testDoc := TestDocument{
Title: "TheDoc -- " + strconv.Itoa(i),
Note: note,
}
_, err := db.Save(testDoc, id, "")
errorify(t, err)
}
}
func errorify(t *testing.T, err error) {
if err != nil {
t.Logf("ERROR: %v", err)
t.Fail()
}
}
func TestPing(t *testing.T) {
conn := getConnection(t)
pingErr := conn.Ping()
errorify(t, pingErr)
}
func TestBadPing(t *testing.T) {
conn, err := NewConnection("unpingable", 1234, timeout)
errorify(t, err)
pingErr := conn.Ping()
if pingErr == nil {
t.Fail()
}
}
func TestGetDBList(t *testing.T) {
conn := getConnection(t)
dbList, err := conn.GetDBList()
errorify(t, err)
if len(dbList) <= 0 {
t.Logf("No results!")
t.Fail()
} else {
for i, dbName := range dbList {
t.Logf("Database %v: %v\n", i, dbName)
}
}
}
func TestCreateDB(t *testing.T) {
conn := getConnection(t)
err := conn.CreateDB("testcreatedb", adminAuth)
errorify(t, err)
//try to create it again --- should fail
err = conn.CreateDB("testcreatedb", adminAuth)
if err == nil {
t.Fail()
}
//now delete it
err = conn.DeleteDB("testcreatedb", adminAuth)
errorify(t, err)
}
func TestSave(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
//Create a new document
theDoc := TestDocument{
Title: "My Document",
Note: "This is my note",
}
db := conn.SelectDB(dbName, nil)
theId := getUuid()
//Save it
t.Logf("Saving first\n")
rev, err := db.Save(theDoc, theId, "")
errorify(t, err)
t.Logf("New Document ID: %s\n", theId)
t.Logf("New Document Rev: %s\n", rev)
t.Logf("New Document Title: %v\n", theDoc.Title)
t.Logf("New Document Note: %v\n", theDoc.Note)
if theDoc.Title != "My Document" ||
theDoc.Note != "This is my note" || rev == "" {
t.Fail()
}
//Now, let's try updating it
theDoc.Note = "A new note"
t.Logf("Saving again\n")
rev, err = db.Save(theDoc, theId, rev)
errorify(t, err)
t.Logf("Updated Document Id: %s\n", theId)
t.Logf("Updated Document Rev: %s\n", rev)
t.Logf("Updated Document Title: %v\n", theDoc.Title)
t.Logf("Updated Document Note: %v\n", theDoc.Note)
if theDoc.Note != "A new note" {
t.Fail()
}
deleteTestDb(t, dbName)
}
func TestAttachment(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
//Create a new document
theDoc := TestDocument{
Title: "My Document",
Note: "This one has attachments",
}
db := conn.SelectDB(dbName, nil)
theId := getUuid()
//Save it
t.Logf("Saving document\n")
rev, err := db.Save(theDoc, theId, "")
errorify(t, err)
t.Logf("New Document Id: %s\n", theId)
t.Logf("New Document Rev: %s\n", rev)
t.Logf("New Document Title: %v\n", theDoc.Title)
t.Logf("New Document Note: %v\n", theDoc.Note)
//Create some content
content := []byte("THIS IS MY ATTACHMENT")
contentReader := bytes.NewReader(content)
//Now Add an attachment
uRev, err := db.SaveAttachment(theId, rev, "attachment", "text/plain", contentReader)
errorify(t, err)
t.Logf("Updated Rev: %s\n", uRev)
//Now try to read it
theContent, err := db.GetAttachment(theId, uRev, "text/plain", "attachment")
errorify(t, err)
defer theContent.Close()
theBytes, err := ioutil.ReadAll(theContent)
errorify(t, err)
t.Logf("how much data: %v\n", len(theBytes))
data := string(theBytes[:])
if data != "THIS IS MY ATTACHMENT" {
t.Fail()
}
t.Logf("The data: %v\n", data)
//Now delete it
dRev, err := db.DeleteAttachment(theId, uRev, "attachment")
errorify(t, err)
t.Logf("Deleted revision: %v\n", dRev)
deleteTestDb(t, dbName)
}
func TestRead(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
db := conn.SelectDB(dbName, nil)
//Create a test doc
theDoc := TestDocument{
Title: "My Document",
Note: "Time to read",
}
emptyDoc := TestDocument{}
//Save it
theId := getUuid()
_, err := db.Save(theDoc, theId, "")
errorify(t, err)
//Now try to read it
rev, err := db.Read(theId, &emptyDoc, nil)
errorify(t, err)
t.Logf("Document Id: %v\n", theId)
t.Logf("Document Rev: %v\n", rev)
t.Logf("Document Title: %v\n", emptyDoc.Title)
t.Logf("Document Note: %v\n", emptyDoc.Note)
deleteTestDb(t, dbName)
}
func TestMultiRead(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
db := conn.SelectDB(dbName, nil)
//Create a test doc
theDoc := TestDocument{
Title: "My Document",
Note: "Time to read",
}
//Save it
theId := getUuid()
_, err := db.Save(theDoc, theId, "")
errorify(t, err)
//Create another test doc
theOtherDoc := TestDocument{
Title: "My Other Document",
Note: "TIme to unread",
}
//Save it
otherId := getUuid()
_, err = db.Save(theOtherDoc, otherId, "")
errorify(t, err)
//Now, try to read them
readDocs := MultiReadResponse{}
keys := []string{theId, otherId}
err = db.ReadMultiple(keys, &readDocs)
errorify(t, err)
t.Logf("\nThe Docs! %v", readDocs)
if len(readDocs.Rows) != 2 {
t.Errorf("Should be 2 results!")
}
deleteTestDb(t, dbName)
}
func TestCopy(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
db := conn.SelectDB(dbName, nil)
//Create a test doc
theDoc := TestDocument{
Title: "My Document",
Note: "Time to read",
}
emptyDoc := TestDocument{}
//Save it
theId := getUuid()
rev, err := db.Save(theDoc, theId, "")
errorify(t, err)
//Now copy it
copyId := getUuid()
copyRev, err := db.Copy(theId, "", copyId)
errorify(t, err)
t.Logf("Document Id: %v\n", theId)
t.Logf("Document Rev: %v\n", rev)
//Now read the copy
_, err = db.Read(copyId, &emptyDoc, nil)
errorify(t, err)
t.Logf("Document Title: %v\n", emptyDoc.Title)
t.Logf("Document Note: %v\n", emptyDoc.Note)
t.Logf("Copied Doc Rev: %v\n", copyRev)
deleteTestDb(t, dbName)
}
func TestDelete(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
db := conn.SelectDB(dbName, nil)
//Create a test doc
theDoc := TestDocument{
Title: "My Document",
Note: "Time to read",
}
theId := getUuid()
rev, err := db.Save(theDoc, theId, "")
errorify(t, err)
//Now delete it
newRev, err := db.Delete(theId, rev)
errorify(t, err)
t.Logf("Document Id: %v\n", theId)
t.Logf("Document Rev: %v\n", rev)
t.Logf("Deleted Rev: %v\n", newRev)
if newRev == "" || newRev == rev {
t.Fail()
}
deleteTestDb(t, dbName)
}
func TestUser(t *testing.T) {
dbName := createTestDb(t)
conn := getConnection(t)
//Save a User
t.Logf("AdminAuth: %v\n", adminAuth)
rev, err := conn.AddUser("turd.ferguson",
"password", []string{"loser"}, adminAuth)
errorify(t, err)
t.Logf("User Rev: %v\n", rev)
if rev == "" {
t.Fail()
}
//check user can access db
db := conn.SelectDB(dbName, &BasicAuth{"turd.ferguson", "password"})
theId := getUuid()
docRev, err := db.Save(&TestDocument{Title: "My doc"}, theId, "")
errorify(t, err)
t.Logf("Granting role to user")
//check session info
authInfo, err := conn.GetAuthInfo(&BasicAuth{"turd.ferguson", "password"})
errorify(t, err)
t.Logf("AuthInfo: %v", authInfo)
if authInfo.UserCtx.Name != "turd.ferguson" {
t.Errorf("UserCtx name wrong: %v", authInfo.UserCtx.Name)
}
//grant a role
rev, err = conn.GrantRole("turd.ferguson",
"fool", adminAuth)
errorify(t, err)
t.Logf("Updated Rev: %v\n", rev)
//read the user
userData := UserRecord{}
rev, err = conn.GetUser("turd.ferguson", &userData, adminAuth)
errorify(t, err)
if len(userData.Roles) != 2 {
t.Error("Not enough roles")
}
t.Logf("Roles: %v", userData.Roles)
//check user can access db
docRev, err = db.Save(&TestDocument{Title: "My doc"}, theId, docRev)
errorify(t, err)
//revoke a role
rev, err = conn.RevokeRole("turd.ferguson",
"loser", adminAuth)
errorify(t, err)
t.Logf("Updated Rev: %v\n", rev)
//read the user
rev, err = conn.GetUser("turd.ferguson", &userData, adminAuth)
errorify(t, err)
if len(userData.Roles) != 1 {
t.Error("should only be 1 role")
}
t.Logf("Roles: %v", userData.Roles)
dRev, err := conn.DeleteUser("turd.ferguson", rev, adminAuth)
errorify(t, err)
t.Logf("Del User Rev: %v\n", dRev)
if rev == dRev || dRev == "" {
t.Fail()
}
deleteTestDb(t, dbName)
}
func TestSecurity(t *testing.T) {
conn := getConnection(t)
dbName := createTestDb(t)
db := conn.SelectDB(dbName, adminAuth)
members := Members{
Users: []string{"joe, bill"},
Roles: []string{"code monkeys"},
}
admins := Members{
Users: []string{"bossman"},
Roles: []string{"boss"},
}
security := Security{
Members: members,
Admins: admins,
}
err := db.SaveSecurity(security)
errorify(t, err)
err = db.AddRole("sales", false)
errorify(t, err)
err = db.AddRole("uberboss", true)
errorify(t, err)
sec, err := db.GetSecurity()
t.Logf("Security: %v\n", sec)
if sec.Admins.Users[0] != "bossman" {
t.Fail()
}
if sec.Admins.Roles[0] != "boss" {
t.Fail()
}
if sec.Admins.Roles[1] != "uberboss" {
t.Errorf("\nAdmin Roles nto right! %v\n", sec.Admins.Roles[1])
}
if sec.Members.Roles[1] != "sales" {
t.Errorf("\nRoles not right! %v\n", sec.Members.Roles[1])
}
errorify(t, err)
err = db.RemoveRole("sales")
errorify(t, err)
err = db.RemoveRole("uberboss")
errorify(t, err)
//try removing a role that ain't there
err = db.RemoveRole("WHATROLE")
errorify(t, err)
sec, err = db.GetSecurity()
t.Logf("Secuirty: %v\n", sec)
if len(sec.Members.Roles) > 1 {
t.Errorf("\nThe Role was not removed: %v\n", sec.Members.Roles)
} else if sec.Members.Roles[0] == "sales" {
t.Errorf("\nThe roles are all messed up: %v\n", sec.Members.Roles)
}
if len(sec.Admins.Roles) > 1 {
t.Errorf("\nThe Admin Role was not removed: %v\n", sec.Admins.Roles)
}
deleteTestDb(t, dbName)
}
func TestSessions(t *testing.T) {
conn := getConnection(t)
dbName := createTestDb(t)
defer deleteTestDb(t, dbName)
//Save a User
t.Logf("AdminAuth: %v\n", adminAuth)
rev, err := conn.AddUser("turd.ferguson",
"password", []string{"loser"}, adminAuth)
errorify(t, err)
t.Logf("User Rev: %v\n", rev)
defer conn.DeleteUser("turd.ferguson", rev, adminAuth)
if rev == "" {
t.Fail()
}
//Create a session for the user
cookieAuth, err := conn.CreateSession("turd.ferguson", "password")
errorify(t, err)
//sleep
time.Sleep(time.Duration(2 * time.Second))
//Create something
db := conn.SelectDB(dbName, cookieAuth)
theId := getUuid()
docRev, err := db.Save(&TestDocument{Title: "The test doc"}, theId, "")
errorify(t, err)
t.Logf("Document Rev: %v", docRev)
t.Logf("Updated Auth: %v", cookieAuth.GetUpdatedAuth()["AuthSession"])
//Delete the user session
err = conn.DestroySession(cookieAuth)
errorify(t, err)
}
func TestSetConfig(t *testing.T) {
conn := getConnection(t)
err := conn.SetConfig("couch_httpd_auth", "timeout", "30", adminAuth)
errorify(t, err)
}
func TestGetConfig(t *testing.T) {
conn := getConnection(t)
val, err := conn.GetConfigOption("couch_httpd_auth", "authentication_db", adminAuth)
errorify(t, err)
if val != "_users" {
t.Error("The auth db is wrong: %v", val)
}
t.Logf("The auth db is : %v", val)
val, err = conn.GetConfigOption("couch_httpd_auth", "auth_cache_size", adminAuth)
if val != "50" {
t.Error("The auth cache size is wrong: %v", val)
}
t.Logf("Auth cache size is : %v", val)
val, err = conn.GetConfigOption("httpd", "allow_jsonp", adminAuth)
if val != "false" {
t.Error("allow jsonp value is wrong: %v", val)
}
t.Logf("Allow JSONP is : %v", val)
}
func TestDesignDocs(t *testing.T) {
conn := getConnection(t)
dbName := createTestDb(t)
db := conn.SelectDB(dbName, adminAuth)
createLotsDocs(t, db)
view := View{
Map: "function(doc) {\n if (doc.Note === \"magenta\"){\n emit(doc)\n }\n}",
}
views := make(map[string]View)
views["find_all_magenta"] = view
lists := make(map[string]string)
lists["getList"] =
`function(head, req){
var row;
var response={
total_rows:0,
offset:0,
rows:[]
};
while(row=getRow()){
response.rows.push(row);
}
response.total_rows = response.rows.length;
send(toJSON(response))
}`
ddoc := DesignDocument{
Language: "javascript",
Views: views,
Lists: lists,
}
rev, err := db.SaveDesignDoc("colors", ddoc, "")
errorify(t, err)
if rev == "" {
t.Fail()
} else {
t.Logf("Rev of design doc: %v\n", rev)
}
//Now, read the design doc
readDdoc := DesignDocument{}
_, err = db.Read("_design/colors", &readDdoc, nil)
if err != nil {
errorify(t, err)
}
result := ViewResponse{}
//now try to query the view
err = db.GetView("colors", "find_all_magenta", &result, nil)
errorify(t, err)
if len(result.Rows) != 5 {
t.Logf("docList length: %v\n", len(result.Rows))
t.Fail()
} else {
t.Logf("Results: %v\n", result.Rows)
}
listResult := ListResponse{}
err = db.GetList("colors", "getList", "find_all_magenta", &listResult, nil)
if err != nil {
t.Logf("ERROR: %v", err)
}
errorify(t, err)
if len(listResult.Rows) != 5 {
t.Logf("List Result: %v\n", listResult)
t.Logf("docList length: %v\n", len(listResult.Rows))
t.Fail()
} else {
t.Logf("List Results: %v\n", listResult)
}
deleteTestDb(t, dbName)
}
//Test for a specific situation I've been having trouble with
func TestAngryCouch(t *testing.T) {
testDoc1 := TestDocument{
Title: "Test Doc 1",
Note: genRandomText(8000),
}
testDoc2 := TestDocument{
Title: "Test Doc 2",
Note: genRandomText(1000),
}
dbName := createTestDb(t)
defer deleteTestDb(t, dbName)
conn := getConnection(t)
db := conn.SelectDB(dbName, nil)
//client := &http.Client{}
id1 := getUuid()
id2 := getUuid()
/*req, err := http.NewRequest(
"PUT",
"http://localhost:5984/"+dbName+"/"+id1,
bytes.NewReader(testBody1),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Expect", "100-continue")*/
rev, err := db.Save(testDoc1, id1, "")
//resp, err := client.Do(req)
errorify(t, err)
//defer resp.Body.Close()
t.Logf("Doc 1 Rev: %v\n", rev)
errorify(t, err)
rev, err = db.Save(testDoc2, id2, "")
t.Logf("Doc 2 Rev: %v\n", rev)
errorify(t, err)
}
func TestFind(t *testing.T) {
conn := getConnection(t)
dbName := createTestDb(t)
db := conn.SelectDB(dbName, adminAuth)
createLotsDocs(t, db)
selector := `{"Note": {"$eq": "magenta"}}`
var selectorObj interface{}
err := json.Unmarshal([]byte(selector), &selectorObj)
if err != nil {
errorify(t, err)
}
//Get the results from find.
findResult := FindResponse{}
params := FindQueryParams{Selector: &selectorObj}
err = db.Find(&findResult, ¶ms)
if err != nil {
errorify(t, err)
}
if len(findResult.Docs) != 5 {
t.Logf("Find Results Length: %v\n", len(findResult.Docs))
t.Fail()
} else {
t.Logf("Results: %v\n", len(findResult.Docs))
}
deleteTestDb(t, dbName)
}