keys_test.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. import (
  16. "errors"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "net/url"
  21. "reflect"
  22. "testing"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. )
  26. func TestV2KeysURLHelper(t *testing.T) {
  27. tests := []struct {
  28. endpoint url.URL
  29. prefix string
  30. key string
  31. want url.URL
  32. }{
  33. // key is empty, no problem
  34. {
  35. endpoint: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"},
  36. prefix: "",
  37. key: "",
  38. want: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"},
  39. },
  40. // key is joined to path
  41. {
  42. endpoint: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"},
  43. prefix: "",
  44. key: "/foo/bar",
  45. want: url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys/foo/bar"},
  46. },
  47. // key is joined to path when path is empty
  48. {
  49. endpoint: url.URL{Scheme: "http", Host: "example.com", Path: ""},
  50. prefix: "",
  51. key: "/foo/bar",
  52. want: url.URL{Scheme: "http", Host: "example.com", Path: "/foo/bar"},
  53. },
  54. // Host field carries through with port
  55. {
  56. endpoint: url.URL{Scheme: "http", Host: "example.com:8080", Path: "/v2/keys"},
  57. prefix: "",
  58. key: "",
  59. want: url.URL{Scheme: "http", Host: "example.com:8080", Path: "/v2/keys"},
  60. },
  61. // Scheme carries through
  62. {
  63. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/v2/keys"},
  64. prefix: "",
  65. key: "",
  66. want: url.URL{Scheme: "https", Host: "example.com", Path: "/v2/keys"},
  67. },
  68. // Prefix is applied
  69. {
  70. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/foo"},
  71. prefix: "/bar",
  72. key: "/baz",
  73. want: url.URL{Scheme: "https", Host: "example.com", Path: "/foo/bar/baz"},
  74. },
  75. // Prefix is joined to path
  76. {
  77. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/foo"},
  78. prefix: "/bar",
  79. key: "",
  80. want: url.URL{Scheme: "https", Host: "example.com", Path: "/foo/bar"},
  81. },
  82. // Keep trailing slash
  83. {
  84. endpoint: url.URL{Scheme: "https", Host: "example.com", Path: "/foo"},
  85. prefix: "/bar",
  86. key: "/baz/",
  87. want: url.URL{Scheme: "https", Host: "example.com", Path: "/foo/bar/baz/"},
  88. },
  89. }
  90. for i, tt := range tests {
  91. got := v2KeysURL(tt.endpoint, tt.prefix, tt.key)
  92. if tt.want != *got {
  93. t.Errorf("#%d: want=%#v, got=%#v", i, tt.want, *got)
  94. }
  95. }
  96. }
  97. func TestGetAction(t *testing.T) {
  98. ep := url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"}
  99. baseWantURL := &url.URL{
  100. Scheme: "http",
  101. Host: "example.com",
  102. Path: "/v2/keys/foo/bar",
  103. }
  104. wantHeader := http.Header{}
  105. tests := []struct {
  106. recursive bool
  107. sorted bool
  108. quorum bool
  109. wantQuery string
  110. }{
  111. {
  112. recursive: false,
  113. sorted: false,
  114. quorum: false,
  115. wantQuery: "quorum=false&recursive=false&sorted=false",
  116. },
  117. {
  118. recursive: true,
  119. sorted: false,
  120. quorum: false,
  121. wantQuery: "quorum=false&recursive=true&sorted=false",
  122. },
  123. {
  124. recursive: false,
  125. sorted: true,
  126. quorum: false,
  127. wantQuery: "quorum=false&recursive=false&sorted=true",
  128. },
  129. {
  130. recursive: true,
  131. sorted: true,
  132. quorum: false,
  133. wantQuery: "quorum=false&recursive=true&sorted=true",
  134. },
  135. {
  136. recursive: false,
  137. sorted: false,
  138. quorum: true,
  139. wantQuery: "quorum=true&recursive=false&sorted=false",
  140. },
  141. }
  142. for i, tt := range tests {
  143. f := getAction{
  144. Key: "/foo/bar",
  145. Recursive: tt.recursive,
  146. Sorted: tt.sorted,
  147. Quorum: tt.quorum,
  148. }
  149. got := *f.HTTPRequest(ep)
  150. wantURL := baseWantURL
  151. wantURL.RawQuery = tt.wantQuery
  152. err := assertRequest(got, "GET", wantURL, wantHeader, nil)
  153. if err != nil {
  154. t.Errorf("#%d: %v", i, err)
  155. }
  156. }
  157. }
  158. func TestWaitAction(t *testing.T) {
  159. ep := url.URL{Scheme: "http", Host: "example.com", Path: "/v2/keys"}
  160. baseWantURL := &url.URL{
  161. Scheme: "http",
  162. Host: "example.com",
  163. Path: "/v2/keys/foo/bar",
  164. }
  165. wantHeader := http.Header{}
  166. tests := []struct {
  167. waitIndex uint64
  168. recursive bool
  169. wantQuery string
  170. }{
  171. {
  172. recursive: false,
  173. waitIndex: uint64(0),
  174. wantQuery: "recursive=false&wait=true&waitIndex=0",
  175. },
  176. {
  177. recursive: false,
  178. waitIndex: uint64(12),
  179. wantQuery: "recursive=false&wait=true&waitIndex=12",
  180. },
  181. {
  182. recursive: true,
  183. waitIndex: uint64(12),
  184. wantQuery: "recursive=true&wait=true&waitIndex=12",
  185. },
  186. }
  187. for i, tt := range tests {
  188. f := waitAction{
  189. Key: "/foo/bar",
  190. WaitIndex: tt.waitIndex,
  191. Recursive: tt.recursive,
  192. }
  193. got := *f.HTTPRequest(ep)
  194. wantURL := baseWantURL
  195. wantURL.RawQuery = tt.wantQuery
  196. err := assertRequest(got, "GET", wantURL, wantHeader, nil)
  197. if err != nil {
  198. t.Errorf("#%d: unexpected error: %#v", i, err)
  199. }
  200. }
  201. }
  202. func TestSetAction(t *testing.T) {
  203. wantHeader := http.Header(map[string][]string{
  204. "Content-Type": {"application/x-www-form-urlencoded"},
  205. })
  206. tests := []struct {
  207. act setAction
  208. wantURL string
  209. wantBody string
  210. }{
  211. // default prefix
  212. {
  213. act: setAction{
  214. Prefix: defaultV2KeysPrefix,
  215. Key: "foo",
  216. },
  217. wantURL: "http://example.com/v2/keys/foo",
  218. wantBody: "value=",
  219. },
  220. // non-default prefix
  221. {
  222. act: setAction{
  223. Prefix: "/pfx",
  224. Key: "foo",
  225. },
  226. wantURL: "http://example.com/pfx/foo",
  227. wantBody: "value=",
  228. },
  229. // no prefix
  230. {
  231. act: setAction{
  232. Key: "foo",
  233. },
  234. wantURL: "http://example.com/foo",
  235. wantBody: "value=",
  236. },
  237. // Key with path separators
  238. {
  239. act: setAction{
  240. Prefix: defaultV2KeysPrefix,
  241. Key: "foo/bar/baz",
  242. },
  243. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  244. wantBody: "value=",
  245. },
  246. // Key with leading slash, Prefix with trailing slash
  247. {
  248. act: setAction{
  249. Prefix: "/foo/",
  250. Key: "/bar",
  251. },
  252. wantURL: "http://example.com/foo/bar",
  253. wantBody: "value=",
  254. },
  255. // Key with trailing slash
  256. {
  257. act: setAction{
  258. Key: "/foo/",
  259. },
  260. wantURL: "http://example.com/foo/",
  261. wantBody: "value=",
  262. },
  263. // Value is set
  264. {
  265. act: setAction{
  266. Key: "foo",
  267. Value: "baz",
  268. },
  269. wantURL: "http://example.com/foo",
  270. wantBody: "value=baz",
  271. },
  272. // PrevExist set, but still ignored
  273. {
  274. act: setAction{
  275. Key: "foo",
  276. PrevExist: PrevIgnore,
  277. },
  278. wantURL: "http://example.com/foo",
  279. wantBody: "value=",
  280. },
  281. // PrevExist set to true
  282. {
  283. act: setAction{
  284. Key: "foo",
  285. PrevExist: PrevExist,
  286. },
  287. wantURL: "http://example.com/foo?prevExist=true",
  288. wantBody: "value=",
  289. },
  290. // PrevExist set to false
  291. {
  292. act: setAction{
  293. Key: "foo",
  294. PrevExist: PrevNoExist,
  295. },
  296. wantURL: "http://example.com/foo?prevExist=false",
  297. wantBody: "value=",
  298. },
  299. // PrevValue is urlencoded
  300. {
  301. act: setAction{
  302. Key: "foo",
  303. PrevValue: "bar baz",
  304. },
  305. wantURL: "http://example.com/foo?prevValue=bar+baz",
  306. wantBody: "value=",
  307. },
  308. // PrevIndex is set
  309. {
  310. act: setAction{
  311. Key: "foo",
  312. PrevIndex: uint64(12),
  313. },
  314. wantURL: "http://example.com/foo?prevIndex=12",
  315. wantBody: "value=",
  316. },
  317. // TTL is set
  318. {
  319. act: setAction{
  320. Key: "foo",
  321. TTL: 3 * time.Minute,
  322. },
  323. wantURL: "http://example.com/foo",
  324. wantBody: "ttl=180&value=",
  325. },
  326. // Dir is set
  327. {
  328. act: setAction{
  329. Key: "foo",
  330. Dir: true,
  331. },
  332. wantURL: "http://example.com/foo?dir=true",
  333. wantBody: "",
  334. },
  335. // Dir is set with a value
  336. {
  337. act: setAction{
  338. Key: "foo",
  339. Value: "bar",
  340. Dir: true,
  341. },
  342. wantURL: "http://example.com/foo?dir=true",
  343. wantBody: "",
  344. },
  345. // Dir is set with PrevExist set to true
  346. {
  347. act: setAction{
  348. Key: "foo",
  349. PrevExist: PrevExist,
  350. Dir: true,
  351. },
  352. wantURL: "http://example.com/foo?dir=true&prevExist=true",
  353. wantBody: "",
  354. },
  355. // Dir is set with PrevValue
  356. {
  357. act: setAction{
  358. Key: "foo",
  359. PrevValue: "bar",
  360. Dir: true,
  361. },
  362. wantURL: "http://example.com/foo?dir=true",
  363. wantBody: "",
  364. },
  365. }
  366. for i, tt := range tests {
  367. u, err := url.Parse(tt.wantURL)
  368. if err != nil {
  369. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  370. }
  371. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  372. if err := assertRequest(*got, "PUT", u, wantHeader, []byte(tt.wantBody)); err != nil {
  373. t.Errorf("#%d: %v", i, err)
  374. }
  375. }
  376. }
  377. func TestCreateInOrderAction(t *testing.T) {
  378. wantHeader := http.Header(map[string][]string{
  379. "Content-Type": {"application/x-www-form-urlencoded"},
  380. })
  381. tests := []struct {
  382. act createInOrderAction
  383. wantURL string
  384. wantBody string
  385. }{
  386. // default prefix
  387. {
  388. act: createInOrderAction{
  389. Prefix: defaultV2KeysPrefix,
  390. Dir: "foo",
  391. },
  392. wantURL: "http://example.com/v2/keys/foo",
  393. wantBody: "value=",
  394. },
  395. // non-default prefix
  396. {
  397. act: createInOrderAction{
  398. Prefix: "/pfx",
  399. Dir: "foo",
  400. },
  401. wantURL: "http://example.com/pfx/foo",
  402. wantBody: "value=",
  403. },
  404. // no prefix
  405. {
  406. act: createInOrderAction{
  407. Dir: "foo",
  408. },
  409. wantURL: "http://example.com/foo",
  410. wantBody: "value=",
  411. },
  412. // Key with path separators
  413. {
  414. act: createInOrderAction{
  415. Prefix: defaultV2KeysPrefix,
  416. Dir: "foo/bar/baz",
  417. },
  418. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  419. wantBody: "value=",
  420. },
  421. // Key with leading slash, Prefix with trailing slash
  422. {
  423. act: createInOrderAction{
  424. Prefix: "/foo/",
  425. Dir: "/bar",
  426. },
  427. wantURL: "http://example.com/foo/bar",
  428. wantBody: "value=",
  429. },
  430. // Key with trailing slash
  431. {
  432. act: createInOrderAction{
  433. Dir: "/foo/",
  434. },
  435. wantURL: "http://example.com/foo/",
  436. wantBody: "value=",
  437. },
  438. // Value is set
  439. {
  440. act: createInOrderAction{
  441. Dir: "foo",
  442. Value: "baz",
  443. },
  444. wantURL: "http://example.com/foo",
  445. wantBody: "value=baz",
  446. },
  447. // TTL is set
  448. {
  449. act: createInOrderAction{
  450. Dir: "foo",
  451. TTL: 3 * time.Minute,
  452. },
  453. wantURL: "http://example.com/foo",
  454. wantBody: "ttl=180&value=",
  455. },
  456. }
  457. for i, tt := range tests {
  458. u, err := url.Parse(tt.wantURL)
  459. if err != nil {
  460. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  461. }
  462. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  463. if err := assertRequest(*got, "POST", u, wantHeader, []byte(tt.wantBody)); err != nil {
  464. t.Errorf("#%d: %v", i, err)
  465. }
  466. }
  467. }
  468. func TestDeleteAction(t *testing.T) {
  469. wantHeader := http.Header(map[string][]string{
  470. "Content-Type": {"application/x-www-form-urlencoded"},
  471. })
  472. tests := []struct {
  473. act deleteAction
  474. wantURL string
  475. }{
  476. // default prefix
  477. {
  478. act: deleteAction{
  479. Prefix: defaultV2KeysPrefix,
  480. Key: "foo",
  481. },
  482. wantURL: "http://example.com/v2/keys/foo",
  483. },
  484. // non-default prefix
  485. {
  486. act: deleteAction{
  487. Prefix: "/pfx",
  488. Key: "foo",
  489. },
  490. wantURL: "http://example.com/pfx/foo",
  491. },
  492. // no prefix
  493. {
  494. act: deleteAction{
  495. Key: "foo",
  496. },
  497. wantURL: "http://example.com/foo",
  498. },
  499. // Key with path separators
  500. {
  501. act: deleteAction{
  502. Prefix: defaultV2KeysPrefix,
  503. Key: "foo/bar/baz",
  504. },
  505. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  506. },
  507. // Key with leading slash, Prefix with trailing slash
  508. {
  509. act: deleteAction{
  510. Prefix: "/foo/",
  511. Key: "/bar",
  512. },
  513. wantURL: "http://example.com/foo/bar",
  514. },
  515. // Key with trailing slash
  516. {
  517. act: deleteAction{
  518. Key: "/foo/",
  519. },
  520. wantURL: "http://example.com/foo/",
  521. },
  522. // Recursive set to true
  523. {
  524. act: deleteAction{
  525. Key: "foo",
  526. Recursive: true,
  527. },
  528. wantURL: "http://example.com/foo?recursive=true",
  529. },
  530. // PrevValue is urlencoded
  531. {
  532. act: deleteAction{
  533. Key: "foo",
  534. PrevValue: "bar baz",
  535. },
  536. wantURL: "http://example.com/foo?prevValue=bar+baz",
  537. },
  538. // PrevIndex is set
  539. {
  540. act: deleteAction{
  541. Key: "foo",
  542. PrevIndex: uint64(12),
  543. },
  544. wantURL: "http://example.com/foo?prevIndex=12",
  545. },
  546. }
  547. for i, tt := range tests {
  548. u, err := url.Parse(tt.wantURL)
  549. if err != nil {
  550. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  551. }
  552. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  553. if err := assertRequest(*got, "DELETE", u, wantHeader, nil); err != nil {
  554. t.Errorf("#%d: %v", i, err)
  555. }
  556. }
  557. }
  558. func assertRequest(got http.Request, wantMethod string, wantURL *url.URL, wantHeader http.Header, wantBody []byte) error {
  559. if wantMethod != got.Method {
  560. return fmt.Errorf("want.Method=%#v got.Method=%#v", wantMethod, got.Method)
  561. }
  562. if !reflect.DeepEqual(wantURL, got.URL) {
  563. return fmt.Errorf("want.URL=%#v got.URL=%#v", wantURL, got.URL)
  564. }
  565. if !reflect.DeepEqual(wantHeader, got.Header) {
  566. return fmt.Errorf("want.Header=%#v got.Header=%#v", wantHeader, got.Header)
  567. }
  568. if got.Body == nil {
  569. if wantBody != nil {
  570. return fmt.Errorf("want.Body=%v got.Body=%v", wantBody, got.Body)
  571. }
  572. } else {
  573. if wantBody == nil {
  574. return fmt.Errorf("want.Body=%v got.Body=%s", wantBody, got.Body)
  575. } else {
  576. gotBytes, err := ioutil.ReadAll(got.Body)
  577. if err != nil {
  578. return err
  579. }
  580. if !reflect.DeepEqual(wantBody, gotBytes) {
  581. return fmt.Errorf("want.Body=%s got.Body=%s", wantBody, gotBytes)
  582. }
  583. }
  584. }
  585. return nil
  586. }
  587. func TestUnmarshalSuccessfulResponse(t *testing.T) {
  588. var expiration time.Time
  589. expiration.UnmarshalText([]byte("2015-04-07T04:40:23.044979686Z"))
  590. tests := []struct {
  591. hdr string
  592. body string
  593. wantRes *Response
  594. wantErr bool
  595. }{
  596. // Neither PrevNode or Node
  597. {
  598. hdr: "1",
  599. body: `{"action":"delete"}`,
  600. wantRes: &Response{Action: "delete", Index: 1},
  601. wantErr: false,
  602. },
  603. // PrevNode
  604. {
  605. hdr: "15",
  606. body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  607. wantRes: &Response{
  608. Action: "delete",
  609. Index: 15,
  610. Node: nil,
  611. PrevNode: &Node{
  612. Key: "/foo",
  613. Value: "bar",
  614. ModifiedIndex: 12,
  615. CreatedIndex: 10,
  616. },
  617. },
  618. wantErr: false,
  619. },
  620. // Node
  621. {
  622. hdr: "15",
  623. body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10, "ttl": 10, "expiration": "2015-04-07T04:40:23.044979686Z"}}`,
  624. wantRes: &Response{
  625. Action: "get",
  626. Index: 15,
  627. Node: &Node{
  628. Key: "/foo",
  629. Value: "bar",
  630. ModifiedIndex: 12,
  631. CreatedIndex: 10,
  632. TTL: 10,
  633. Expiration: &expiration,
  634. },
  635. PrevNode: nil,
  636. },
  637. wantErr: false,
  638. },
  639. // Node Dir
  640. {
  641. hdr: "15",
  642. body: `{"action":"get", "node": {"key": "/foo", "dir": true, "modifiedIndex": 12, "createdIndex": 10}}`,
  643. wantRes: &Response{
  644. Action: "get",
  645. Index: 15,
  646. Node: &Node{
  647. Key: "/foo",
  648. Dir: true,
  649. ModifiedIndex: 12,
  650. CreatedIndex: 10,
  651. },
  652. PrevNode: nil,
  653. },
  654. wantErr: false,
  655. },
  656. // PrevNode and Node
  657. {
  658. hdr: "15",
  659. body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  660. wantRes: &Response{
  661. Action: "update",
  662. Index: 15,
  663. PrevNode: &Node{
  664. Key: "/foo",
  665. Value: "baz",
  666. ModifiedIndex: 10,
  667. CreatedIndex: 10,
  668. },
  669. Node: &Node{
  670. Key: "/foo",
  671. Value: "bar",
  672. ModifiedIndex: 12,
  673. CreatedIndex: 10,
  674. },
  675. },
  676. wantErr: false,
  677. },
  678. // Garbage in body
  679. {
  680. hdr: "",
  681. body: `garbage`,
  682. wantRes: nil,
  683. wantErr: true,
  684. },
  685. // non-integer index
  686. {
  687. hdr: "poo",
  688. body: `{}`,
  689. wantRes: nil,
  690. wantErr: true,
  691. },
  692. }
  693. for i, tt := range tests {
  694. h := make(http.Header)
  695. h.Add("X-Etcd-Index", tt.hdr)
  696. res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body))
  697. if tt.wantErr != (err != nil) {
  698. t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err)
  699. }
  700. if (res == nil) != (tt.wantRes == nil) {
  701. t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes)
  702. continue
  703. } else if tt.wantRes == nil {
  704. // expected and successfully got nil response
  705. continue
  706. }
  707. if res.Action != tt.wantRes.Action {
  708. t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action)
  709. }
  710. if res.Index != tt.wantRes.Index {
  711. t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index)
  712. }
  713. if !reflect.DeepEqual(res.Node, tt.wantRes.Node) {
  714. t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node)
  715. }
  716. }
  717. }
  718. func TestUnmarshalFailedKeysResponse(t *testing.T) {
  719. body := []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`)
  720. wantErr := Error{
  721. Code: 100,
  722. Message: "Key not found",
  723. Cause: "/foo",
  724. Index: uint64(18),
  725. }
  726. gotErr := unmarshalFailedKeysResponse(body)
  727. if !reflect.DeepEqual(wantErr, gotErr) {
  728. t.Errorf("unexpected error: want=%#v got=%#v", wantErr, gotErr)
  729. }
  730. }
  731. func TestUnmarshalFailedKeysResponseBadJSON(t *testing.T) {
  732. err := unmarshalFailedKeysResponse([]byte(`{"er`))
  733. if err == nil {
  734. t.Errorf("got nil error")
  735. } else if _, ok := err.(Error); ok {
  736. t.Errorf("error is of incorrect type *Error: %#v", err)
  737. }
  738. }
  739. func TestHTTPWatcherNextWaitAction(t *testing.T) {
  740. initAction := waitAction{
  741. Prefix: "/pants",
  742. Key: "/foo/bar",
  743. Recursive: true,
  744. WaitIndex: 19,
  745. }
  746. client := &actionAssertingHTTPClient{
  747. t: t,
  748. act: &initAction,
  749. resp: http.Response{
  750. StatusCode: http.StatusOK,
  751. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  752. },
  753. body: []byte(`{"action":"update","node":{"key":"/pants/foo/bar/baz","value":"snarf","modifiedIndex":21,"createdIndex":19},"prevNode":{"key":"/pants/foo/bar/baz","value":"snazz","modifiedIndex":20,"createdIndex":19}}`),
  754. }
  755. wantResponse := &Response{
  756. Action: "update",
  757. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(21)},
  758. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  759. Index: uint64(42),
  760. }
  761. wantNextWait := waitAction{
  762. Prefix: "/pants",
  763. Key: "/foo/bar",
  764. Recursive: true,
  765. WaitIndex: 22,
  766. }
  767. watcher := &httpWatcher{
  768. client: client,
  769. nextWait: initAction,
  770. }
  771. resp, err := watcher.Next(context.Background())
  772. if err != nil {
  773. t.Errorf("non-nil error: %#v", err)
  774. }
  775. if !reflect.DeepEqual(wantResponse, resp) {
  776. t.Errorf("received incorrect Response: want=%#v got=%#v", wantResponse, resp)
  777. }
  778. if !reflect.DeepEqual(wantNextWait, watcher.nextWait) {
  779. t.Errorf("nextWait incorrect: want=%#v got=%#v", wantNextWait, watcher.nextWait)
  780. }
  781. }
  782. func TestHTTPWatcherNextFail(t *testing.T) {
  783. tests := []httpClient{
  784. // generic HTTP client failure
  785. &staticHTTPClient{
  786. err: errors.New("fail!"),
  787. },
  788. // unusable status code
  789. &staticHTTPClient{
  790. resp: http.Response{
  791. StatusCode: http.StatusTeapot,
  792. },
  793. },
  794. // etcd Error response
  795. &staticHTTPClient{
  796. resp: http.Response{
  797. StatusCode: http.StatusNotFound,
  798. },
  799. body: []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`),
  800. },
  801. }
  802. for i, tt := range tests {
  803. act := waitAction{
  804. Prefix: "/pants",
  805. Key: "/foo/bar",
  806. Recursive: true,
  807. WaitIndex: 19,
  808. }
  809. watcher := &httpWatcher{
  810. client: tt,
  811. nextWait: act,
  812. }
  813. resp, err := watcher.Next(context.Background())
  814. if err == nil {
  815. t.Errorf("#%d: expected non-nil error", i)
  816. }
  817. if resp != nil {
  818. t.Errorf("#%d: expected nil Response, got %#v", i, resp)
  819. }
  820. if !reflect.DeepEqual(act, watcher.nextWait) {
  821. t.Errorf("#%d: nextWait changed: want=%#v got=%#v", i, act, watcher.nextWait)
  822. }
  823. }
  824. }
  825. func TestHTTPKeysAPIWatcherAction(t *testing.T) {
  826. tests := []struct {
  827. key string
  828. opts *WatcherOptions
  829. want waitAction
  830. }{
  831. {
  832. key: "/foo",
  833. opts: nil,
  834. want: waitAction{
  835. Key: "/foo",
  836. Recursive: false,
  837. WaitIndex: 0,
  838. },
  839. },
  840. {
  841. key: "/foo",
  842. opts: &WatcherOptions{
  843. Recursive: false,
  844. AfterIndex: 0,
  845. },
  846. want: waitAction{
  847. Key: "/foo",
  848. Recursive: false,
  849. WaitIndex: 0,
  850. },
  851. },
  852. {
  853. key: "/foo",
  854. opts: &WatcherOptions{
  855. Recursive: true,
  856. AfterIndex: 0,
  857. },
  858. want: waitAction{
  859. Key: "/foo",
  860. Recursive: true,
  861. WaitIndex: 0,
  862. },
  863. },
  864. {
  865. key: "/foo",
  866. opts: &WatcherOptions{
  867. Recursive: false,
  868. AfterIndex: 19,
  869. },
  870. want: waitAction{
  871. Key: "/foo",
  872. Recursive: false,
  873. WaitIndex: 20,
  874. },
  875. },
  876. }
  877. for i, tt := range tests {
  878. kAPI := &httpKeysAPI{
  879. client: &staticHTTPClient{err: errors.New("fail!")},
  880. }
  881. want := &httpWatcher{
  882. client: &staticHTTPClient{err: errors.New("fail!")},
  883. nextWait: tt.want,
  884. }
  885. got := kAPI.Watcher(tt.key, tt.opts)
  886. if !reflect.DeepEqual(want, got) {
  887. t.Errorf("#%d: incorrect watcher: want=%#v got=%#v", i, want, got)
  888. }
  889. }
  890. }
  891. func TestHTTPKeysAPISetAction(t *testing.T) {
  892. tests := []struct {
  893. key string
  894. value string
  895. opts *SetOptions
  896. wantAction httpAction
  897. }{
  898. // nil SetOptions
  899. {
  900. key: "/foo",
  901. value: "bar",
  902. opts: nil,
  903. wantAction: &setAction{
  904. Key: "/foo",
  905. Value: "bar",
  906. PrevValue: "",
  907. PrevIndex: 0,
  908. PrevExist: PrevIgnore,
  909. TTL: 0,
  910. },
  911. },
  912. // empty SetOptions
  913. {
  914. key: "/foo",
  915. value: "bar",
  916. opts: &SetOptions{},
  917. wantAction: &setAction{
  918. Key: "/foo",
  919. Value: "bar",
  920. PrevValue: "",
  921. PrevIndex: 0,
  922. PrevExist: PrevIgnore,
  923. TTL: 0,
  924. },
  925. },
  926. // populated SetOptions
  927. {
  928. key: "/foo",
  929. value: "bar",
  930. opts: &SetOptions{
  931. PrevValue: "baz",
  932. PrevIndex: 13,
  933. PrevExist: PrevExist,
  934. TTL: time.Minute,
  935. Dir: true,
  936. },
  937. wantAction: &setAction{
  938. Key: "/foo",
  939. Value: "bar",
  940. PrevValue: "baz",
  941. PrevIndex: 13,
  942. PrevExist: PrevExist,
  943. TTL: time.Minute,
  944. Dir: true,
  945. },
  946. },
  947. }
  948. for i, tt := range tests {
  949. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  950. kAPI := httpKeysAPI{client: client}
  951. kAPI.Set(context.Background(), tt.key, tt.value, tt.opts)
  952. }
  953. }
  954. func TestHTTPKeysAPISetError(t *testing.T) {
  955. tests := []httpClient{
  956. // generic HTTP client failure
  957. &staticHTTPClient{
  958. err: errors.New("fail!"),
  959. },
  960. // unusable status code
  961. &staticHTTPClient{
  962. resp: http.Response{
  963. StatusCode: http.StatusTeapot,
  964. },
  965. },
  966. // etcd Error response
  967. &staticHTTPClient{
  968. resp: http.Response{
  969. StatusCode: http.StatusInternalServerError,
  970. },
  971. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  972. },
  973. }
  974. for i, tt := range tests {
  975. kAPI := httpKeysAPI{client: tt}
  976. resp, err := kAPI.Set(context.Background(), "/foo", "bar", nil)
  977. if err == nil {
  978. t.Errorf("#%d: received nil error", i)
  979. }
  980. if resp != nil {
  981. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  982. }
  983. }
  984. }
  985. func TestHTTPKeysAPISetResponse(t *testing.T) {
  986. client := &staticHTTPClient{
  987. resp: http.Response{
  988. StatusCode: http.StatusOK,
  989. Header: http.Header{"X-Etcd-Index": []string{"21"}},
  990. },
  991. body: []byte(`{"action":"set","node":{"key":"/pants/foo/bar/baz","value":"snarf","modifiedIndex":21,"createdIndex":21},"prevNode":{"key":"/pants/foo/bar/baz","value":"snazz","modifiedIndex":20,"createdIndex":19}}`),
  992. }
  993. wantResponse := &Response{
  994. Action: "set",
  995. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(21), ModifiedIndex: uint64(21)},
  996. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  997. Index: uint64(21),
  998. }
  999. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1000. resp, err := kAPI.Set(context.Background(), "/foo/bar/baz", "snarf", nil)
  1001. if err != nil {
  1002. t.Errorf("non-nil error: %#v", err)
  1003. }
  1004. if !reflect.DeepEqual(wantResponse, resp) {
  1005. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1006. }
  1007. }
  1008. func TestHTTPKeysAPIGetAction(t *testing.T) {
  1009. tests := []struct {
  1010. key string
  1011. opts *GetOptions
  1012. wantAction httpAction
  1013. }{
  1014. // nil GetOptions
  1015. {
  1016. key: "/foo",
  1017. opts: nil,
  1018. wantAction: &getAction{
  1019. Key: "/foo",
  1020. Sorted: false,
  1021. Recursive: false,
  1022. },
  1023. },
  1024. // empty GetOptions
  1025. {
  1026. key: "/foo",
  1027. opts: &GetOptions{},
  1028. wantAction: &getAction{
  1029. Key: "/foo",
  1030. Sorted: false,
  1031. Recursive: false,
  1032. },
  1033. },
  1034. // populated GetOptions
  1035. {
  1036. key: "/foo",
  1037. opts: &GetOptions{
  1038. Sort: true,
  1039. Recursive: true,
  1040. Quorum: true,
  1041. },
  1042. wantAction: &getAction{
  1043. Key: "/foo",
  1044. Sorted: true,
  1045. Recursive: true,
  1046. Quorum: true,
  1047. },
  1048. },
  1049. }
  1050. for i, tt := range tests {
  1051. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1052. kAPI := httpKeysAPI{client: client}
  1053. kAPI.Get(context.Background(), tt.key, tt.opts)
  1054. }
  1055. }
  1056. func TestHTTPKeysAPIGetError(t *testing.T) {
  1057. tests := []httpClient{
  1058. // generic HTTP client failure
  1059. &staticHTTPClient{
  1060. err: errors.New("fail!"),
  1061. },
  1062. // unusable status code
  1063. &staticHTTPClient{
  1064. resp: http.Response{
  1065. StatusCode: http.StatusTeapot,
  1066. },
  1067. },
  1068. // etcd Error response
  1069. &staticHTTPClient{
  1070. resp: http.Response{
  1071. StatusCode: http.StatusInternalServerError,
  1072. },
  1073. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1074. },
  1075. }
  1076. for i, tt := range tests {
  1077. kAPI := httpKeysAPI{client: tt}
  1078. resp, err := kAPI.Get(context.Background(), "/foo", nil)
  1079. if err == nil {
  1080. t.Errorf("#%d: received nil error", i)
  1081. }
  1082. if resp != nil {
  1083. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1084. }
  1085. }
  1086. }
  1087. func TestHTTPKeysAPIGetResponse(t *testing.T) {
  1088. client := &staticHTTPClient{
  1089. resp: http.Response{
  1090. StatusCode: http.StatusOK,
  1091. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  1092. },
  1093. body: []byte(`{"action":"get","node":{"key":"/pants/foo/bar","modifiedIndex":25,"createdIndex":19,"nodes":[{"key":"/pants/foo/bar/baz","value":"snarf","createdIndex":21,"modifiedIndex":25}]}}`),
  1094. }
  1095. wantResponse := &Response{
  1096. Action: "get",
  1097. Node: &Node{
  1098. Key: "/pants/foo/bar",
  1099. Nodes: []*Node{
  1100. {Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: 21, ModifiedIndex: 25},
  1101. },
  1102. CreatedIndex: uint64(19),
  1103. ModifiedIndex: uint64(25),
  1104. },
  1105. Index: uint64(42),
  1106. }
  1107. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1108. resp, err := kAPI.Get(context.Background(), "/foo/bar", &GetOptions{Recursive: true})
  1109. if err != nil {
  1110. t.Errorf("non-nil error: %#v", err)
  1111. }
  1112. if !reflect.DeepEqual(wantResponse, resp) {
  1113. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1114. }
  1115. }
  1116. func TestHTTPKeysAPIDeleteAction(t *testing.T) {
  1117. tests := []struct {
  1118. key string
  1119. value string
  1120. opts *DeleteOptions
  1121. wantAction httpAction
  1122. }{
  1123. // nil DeleteOptions
  1124. {
  1125. key: "/foo",
  1126. opts: nil,
  1127. wantAction: &deleteAction{
  1128. Key: "/foo",
  1129. PrevValue: "",
  1130. PrevIndex: 0,
  1131. Recursive: false,
  1132. },
  1133. },
  1134. // empty DeleteOptions
  1135. {
  1136. key: "/foo",
  1137. opts: &DeleteOptions{},
  1138. wantAction: &deleteAction{
  1139. Key: "/foo",
  1140. PrevValue: "",
  1141. PrevIndex: 0,
  1142. Recursive: false,
  1143. },
  1144. },
  1145. // populated DeleteOptions
  1146. {
  1147. key: "/foo",
  1148. opts: &DeleteOptions{
  1149. PrevValue: "baz",
  1150. PrevIndex: 13,
  1151. Recursive: true,
  1152. },
  1153. wantAction: &deleteAction{
  1154. Key: "/foo",
  1155. PrevValue: "baz",
  1156. PrevIndex: 13,
  1157. Recursive: true,
  1158. },
  1159. },
  1160. }
  1161. for i, tt := range tests {
  1162. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1163. kAPI := httpKeysAPI{client: client}
  1164. kAPI.Delete(context.Background(), tt.key, tt.opts)
  1165. }
  1166. }
  1167. func TestHTTPKeysAPIDeleteError(t *testing.T) {
  1168. tests := []httpClient{
  1169. // generic HTTP client failure
  1170. &staticHTTPClient{
  1171. err: errors.New("fail!"),
  1172. },
  1173. // unusable status code
  1174. &staticHTTPClient{
  1175. resp: http.Response{
  1176. StatusCode: http.StatusTeapot,
  1177. },
  1178. },
  1179. // etcd Error response
  1180. &staticHTTPClient{
  1181. resp: http.Response{
  1182. StatusCode: http.StatusInternalServerError,
  1183. },
  1184. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1185. },
  1186. }
  1187. for i, tt := range tests {
  1188. kAPI := httpKeysAPI{client: tt}
  1189. resp, err := kAPI.Delete(context.Background(), "/foo", nil)
  1190. if err == nil {
  1191. t.Errorf("#%d: received nil error", i)
  1192. }
  1193. if resp != nil {
  1194. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1195. }
  1196. }
  1197. }
  1198. func TestHTTPKeysAPIDeleteResponse(t *testing.T) {
  1199. client := &staticHTTPClient{
  1200. resp: http.Response{
  1201. StatusCode: http.StatusOK,
  1202. Header: http.Header{"X-Etcd-Index": []string{"22"}},
  1203. },
  1204. body: []byte(`{"action":"delete","node":{"key":"/pants/foo/bar/baz","value":"snarf","modifiedIndex":22,"createdIndex":19},"prevNode":{"key":"/pants/foo/bar/baz","value":"snazz","modifiedIndex":20,"createdIndex":19}}`),
  1205. }
  1206. wantResponse := &Response{
  1207. Action: "delete",
  1208. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(22)},
  1209. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1210. Index: uint64(22),
  1211. }
  1212. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1213. resp, err := kAPI.Delete(context.Background(), "/foo/bar/baz", nil)
  1214. if err != nil {
  1215. t.Errorf("non-nil error: %#v", err)
  1216. }
  1217. if !reflect.DeepEqual(wantResponse, resp) {
  1218. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1219. }
  1220. }
  1221. func TestHTTPKeysAPICreateAction(t *testing.T) {
  1222. act := &setAction{
  1223. Key: "/foo",
  1224. Value: "bar",
  1225. PrevExist: PrevNoExist,
  1226. PrevIndex: 0,
  1227. PrevValue: "",
  1228. TTL: 0,
  1229. }
  1230. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1231. kAPI.Create(context.Background(), "/foo", "bar")
  1232. }
  1233. func TestHTTPKeysAPICreateInOrderAction(t *testing.T) {
  1234. act := &createInOrderAction{
  1235. Dir: "/foo",
  1236. Value: "bar",
  1237. TTL: 0,
  1238. }
  1239. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1240. kAPI.CreateInOrder(context.Background(), "/foo", "bar", nil)
  1241. }
  1242. func TestHTTPKeysAPIUpdateAction(t *testing.T) {
  1243. act := &setAction{
  1244. Key: "/foo",
  1245. Value: "bar",
  1246. PrevExist: PrevExist,
  1247. PrevIndex: 0,
  1248. PrevValue: "",
  1249. TTL: 0,
  1250. }
  1251. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1252. kAPI.Update(context.Background(), "/foo", "bar")
  1253. }
  1254. func TestNodeTTLDuration(t *testing.T) {
  1255. tests := []struct {
  1256. node *Node
  1257. want time.Duration
  1258. }{
  1259. {
  1260. node: &Node{TTL: 0},
  1261. want: 0,
  1262. },
  1263. {
  1264. node: &Node{TTL: 97},
  1265. want: 97 * time.Second,
  1266. },
  1267. }
  1268. for i, tt := range tests {
  1269. got := tt.node.TTLDuration()
  1270. if tt.want != got {
  1271. t.Errorf("#%d: incorrect duration: want=%v got=%v", i, tt.want, got)
  1272. }
  1273. }
  1274. }