keys_test.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. // Copyright 2015 The etcd Authors
  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. "context"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "net/url"
  22. "reflect"
  23. "testing"
  24. "time"
  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. // Refresh is set
  327. {
  328. act: setAction{
  329. Key: "foo",
  330. TTL: 3 * time.Minute,
  331. Refresh: true,
  332. },
  333. wantURL: "http://example.com/foo",
  334. wantBody: "refresh=true&ttl=180&value=",
  335. },
  336. // Dir is set
  337. {
  338. act: setAction{
  339. Key: "foo",
  340. Dir: true,
  341. },
  342. wantURL: "http://example.com/foo?dir=true",
  343. wantBody: "",
  344. },
  345. // Dir is set with a value
  346. {
  347. act: setAction{
  348. Key: "foo",
  349. Value: "bar",
  350. Dir: true,
  351. },
  352. wantURL: "http://example.com/foo?dir=true",
  353. wantBody: "",
  354. },
  355. // Dir is set with PrevExist set to true
  356. {
  357. act: setAction{
  358. Key: "foo",
  359. PrevExist: PrevExist,
  360. Dir: true,
  361. },
  362. wantURL: "http://example.com/foo?dir=true&prevExist=true",
  363. wantBody: "",
  364. },
  365. // Dir is set with PrevValue
  366. {
  367. act: setAction{
  368. Key: "foo",
  369. PrevValue: "bar",
  370. Dir: true,
  371. },
  372. wantURL: "http://example.com/foo?dir=true",
  373. wantBody: "",
  374. },
  375. // NoValueOnSuccess is set
  376. {
  377. act: setAction{
  378. Key: "foo",
  379. NoValueOnSuccess: true,
  380. },
  381. wantURL: "http://example.com/foo?noValueOnSuccess=true",
  382. wantBody: "value=",
  383. },
  384. }
  385. for i, tt := range tests {
  386. u, err := url.Parse(tt.wantURL)
  387. if err != nil {
  388. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  389. }
  390. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  391. if err := assertRequest(*got, "PUT", u, wantHeader, []byte(tt.wantBody)); err != nil {
  392. t.Errorf("#%d: %v", i, err)
  393. }
  394. }
  395. }
  396. func TestCreateInOrderAction(t *testing.T) {
  397. wantHeader := http.Header(map[string][]string{
  398. "Content-Type": {"application/x-www-form-urlencoded"},
  399. })
  400. tests := []struct {
  401. act createInOrderAction
  402. wantURL string
  403. wantBody string
  404. }{
  405. // default prefix
  406. {
  407. act: createInOrderAction{
  408. Prefix: defaultV2KeysPrefix,
  409. Dir: "foo",
  410. },
  411. wantURL: "http://example.com/v2/keys/foo",
  412. wantBody: "value=",
  413. },
  414. // non-default prefix
  415. {
  416. act: createInOrderAction{
  417. Prefix: "/pfx",
  418. Dir: "foo",
  419. },
  420. wantURL: "http://example.com/pfx/foo",
  421. wantBody: "value=",
  422. },
  423. // no prefix
  424. {
  425. act: createInOrderAction{
  426. Dir: "foo",
  427. },
  428. wantURL: "http://example.com/foo",
  429. wantBody: "value=",
  430. },
  431. // Key with path separators
  432. {
  433. act: createInOrderAction{
  434. Prefix: defaultV2KeysPrefix,
  435. Dir: "foo/bar/baz",
  436. },
  437. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  438. wantBody: "value=",
  439. },
  440. // Key with leading slash, Prefix with trailing slash
  441. {
  442. act: createInOrderAction{
  443. Prefix: "/foo/",
  444. Dir: "/bar",
  445. },
  446. wantURL: "http://example.com/foo/bar",
  447. wantBody: "value=",
  448. },
  449. // Key with trailing slash
  450. {
  451. act: createInOrderAction{
  452. Dir: "/foo/",
  453. },
  454. wantURL: "http://example.com/foo/",
  455. wantBody: "value=",
  456. },
  457. // Value is set
  458. {
  459. act: createInOrderAction{
  460. Dir: "foo",
  461. Value: "baz",
  462. },
  463. wantURL: "http://example.com/foo",
  464. wantBody: "value=baz",
  465. },
  466. // TTL is set
  467. {
  468. act: createInOrderAction{
  469. Dir: "foo",
  470. TTL: 3 * time.Minute,
  471. },
  472. wantURL: "http://example.com/foo",
  473. wantBody: "ttl=180&value=",
  474. },
  475. }
  476. for i, tt := range tests {
  477. u, err := url.Parse(tt.wantURL)
  478. if err != nil {
  479. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  480. }
  481. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  482. if err := assertRequest(*got, "POST", u, wantHeader, []byte(tt.wantBody)); err != nil {
  483. t.Errorf("#%d: %v", i, err)
  484. }
  485. }
  486. }
  487. func TestDeleteAction(t *testing.T) {
  488. wantHeader := http.Header(map[string][]string{
  489. "Content-Type": {"application/x-www-form-urlencoded"},
  490. })
  491. tests := []struct {
  492. act deleteAction
  493. wantURL string
  494. }{
  495. // default prefix
  496. {
  497. act: deleteAction{
  498. Prefix: defaultV2KeysPrefix,
  499. Key: "foo",
  500. },
  501. wantURL: "http://example.com/v2/keys/foo",
  502. },
  503. // non-default prefix
  504. {
  505. act: deleteAction{
  506. Prefix: "/pfx",
  507. Key: "foo",
  508. },
  509. wantURL: "http://example.com/pfx/foo",
  510. },
  511. // no prefix
  512. {
  513. act: deleteAction{
  514. Key: "foo",
  515. },
  516. wantURL: "http://example.com/foo",
  517. },
  518. // Key with path separators
  519. {
  520. act: deleteAction{
  521. Prefix: defaultV2KeysPrefix,
  522. Key: "foo/bar/baz",
  523. },
  524. wantURL: "http://example.com/v2/keys/foo/bar/baz",
  525. },
  526. // Key with leading slash, Prefix with trailing slash
  527. {
  528. act: deleteAction{
  529. Prefix: "/foo/",
  530. Key: "/bar",
  531. },
  532. wantURL: "http://example.com/foo/bar",
  533. },
  534. // Key with trailing slash
  535. {
  536. act: deleteAction{
  537. Key: "/foo/",
  538. },
  539. wantURL: "http://example.com/foo/",
  540. },
  541. // Recursive set to true
  542. {
  543. act: deleteAction{
  544. Key: "foo",
  545. Recursive: true,
  546. },
  547. wantURL: "http://example.com/foo?recursive=true",
  548. },
  549. // PrevValue is urlencoded
  550. {
  551. act: deleteAction{
  552. Key: "foo",
  553. PrevValue: "bar baz",
  554. },
  555. wantURL: "http://example.com/foo?prevValue=bar+baz",
  556. },
  557. // PrevIndex is set
  558. {
  559. act: deleteAction{
  560. Key: "foo",
  561. PrevIndex: uint64(12),
  562. },
  563. wantURL: "http://example.com/foo?prevIndex=12",
  564. },
  565. }
  566. for i, tt := range tests {
  567. u, err := url.Parse(tt.wantURL)
  568. if err != nil {
  569. t.Errorf("#%d: unable to use wantURL fixture: %v", i, err)
  570. }
  571. got := tt.act.HTTPRequest(url.URL{Scheme: "http", Host: "example.com"})
  572. if err := assertRequest(*got, "DELETE", u, wantHeader, nil); err != nil {
  573. t.Errorf("#%d: %v", i, err)
  574. }
  575. }
  576. }
  577. func assertRequest(got http.Request, wantMethod string, wantURL *url.URL, wantHeader http.Header, wantBody []byte) error {
  578. if wantMethod != got.Method {
  579. return fmt.Errorf("want.Method=%#v got.Method=%#v", wantMethod, got.Method)
  580. }
  581. if !reflect.DeepEqual(wantURL, got.URL) {
  582. return fmt.Errorf("want.URL=%#v got.URL=%#v", wantURL, got.URL)
  583. }
  584. if !reflect.DeepEqual(wantHeader, got.Header) {
  585. return fmt.Errorf("want.Header=%#v got.Header=%#v", wantHeader, got.Header)
  586. }
  587. if got.Body == nil {
  588. if wantBody != nil {
  589. return fmt.Errorf("want.Body=%v got.Body=%v", wantBody, got.Body)
  590. }
  591. } else {
  592. if wantBody == nil {
  593. return fmt.Errorf("want.Body=%v got.Body=%s", wantBody, got.Body)
  594. }
  595. gotBytes, err := ioutil.ReadAll(got.Body)
  596. if err != nil {
  597. return err
  598. }
  599. if !reflect.DeepEqual(wantBody, gotBytes) {
  600. return fmt.Errorf("want.Body=%s got.Body=%s", wantBody, gotBytes)
  601. }
  602. }
  603. return nil
  604. }
  605. func TestUnmarshalSuccessfulResponse(t *testing.T) {
  606. var expiration time.Time
  607. expiration.UnmarshalText([]byte("2015-04-07T04:40:23.044979686Z"))
  608. tests := []struct {
  609. indexHdr string
  610. clusterIDHdr string
  611. body string
  612. wantRes *Response
  613. wantErr bool
  614. }{
  615. // Neither PrevNode or Node
  616. {
  617. indexHdr: "1",
  618. body: `{"action":"delete"}`,
  619. wantRes: &Response{Action: "delete", Index: 1},
  620. wantErr: false,
  621. },
  622. // PrevNode
  623. {
  624. indexHdr: "15",
  625. body: `{"action":"delete", "prevNode": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  626. wantRes: &Response{
  627. Action: "delete",
  628. Index: 15,
  629. Node: nil,
  630. PrevNode: &Node{
  631. Key: "/foo",
  632. Value: "bar",
  633. ModifiedIndex: 12,
  634. CreatedIndex: 10,
  635. },
  636. },
  637. wantErr: false,
  638. },
  639. // Node
  640. {
  641. indexHdr: "15",
  642. body: `{"action":"get", "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10, "ttl": 10, "expiration": "2015-04-07T04:40:23.044979686Z"}}`,
  643. wantRes: &Response{
  644. Action: "get",
  645. Index: 15,
  646. Node: &Node{
  647. Key: "/foo",
  648. Value: "bar",
  649. ModifiedIndex: 12,
  650. CreatedIndex: 10,
  651. TTL: 10,
  652. Expiration: &expiration,
  653. },
  654. PrevNode: nil,
  655. },
  656. wantErr: false,
  657. },
  658. // Node Dir
  659. {
  660. indexHdr: "15",
  661. clusterIDHdr: "abcdef",
  662. body: `{"action":"get", "node": {"key": "/foo", "dir": true, "modifiedIndex": 12, "createdIndex": 10}}`,
  663. wantRes: &Response{
  664. Action: "get",
  665. Index: 15,
  666. Node: &Node{
  667. Key: "/foo",
  668. Dir: true,
  669. ModifiedIndex: 12,
  670. CreatedIndex: 10,
  671. },
  672. PrevNode: nil,
  673. ClusterID: "abcdef",
  674. },
  675. wantErr: false,
  676. },
  677. // PrevNode and Node
  678. {
  679. indexHdr: "15",
  680. body: `{"action":"update", "prevNode": {"key": "/foo", "value": "baz", "modifiedIndex": 10, "createdIndex": 10}, "node": {"key": "/foo", "value": "bar", "modifiedIndex": 12, "createdIndex": 10}}`,
  681. wantRes: &Response{
  682. Action: "update",
  683. Index: 15,
  684. PrevNode: &Node{
  685. Key: "/foo",
  686. Value: "baz",
  687. ModifiedIndex: 10,
  688. CreatedIndex: 10,
  689. },
  690. Node: &Node{
  691. Key: "/foo",
  692. Value: "bar",
  693. ModifiedIndex: 12,
  694. CreatedIndex: 10,
  695. },
  696. },
  697. wantErr: false,
  698. },
  699. // Garbage in body
  700. {
  701. indexHdr: "",
  702. body: `garbage`,
  703. wantRes: nil,
  704. wantErr: true,
  705. },
  706. // non-integer index
  707. {
  708. indexHdr: "poo",
  709. body: `{}`,
  710. wantRes: nil,
  711. wantErr: true,
  712. },
  713. }
  714. for i, tt := range tests {
  715. h := make(http.Header)
  716. h.Add("X-Etcd-Index", tt.indexHdr)
  717. res, err := unmarshalSuccessfulKeysResponse(h, []byte(tt.body))
  718. if tt.wantErr != (err != nil) {
  719. t.Errorf("#%d: wantErr=%t, err=%v", i, tt.wantErr, err)
  720. }
  721. if (res == nil) != (tt.wantRes == nil) {
  722. t.Errorf("#%d: received res=%#v, but expected res=%#v", i, res, tt.wantRes)
  723. continue
  724. } else if tt.wantRes == nil {
  725. // expected and successfully got nil response
  726. continue
  727. }
  728. if res.Action != tt.wantRes.Action {
  729. t.Errorf("#%d: Action=%s, expected %s", i, res.Action, tt.wantRes.Action)
  730. }
  731. if res.Index != tt.wantRes.Index {
  732. t.Errorf("#%d: Index=%d, expected %d", i, res.Index, tt.wantRes.Index)
  733. }
  734. if !reflect.DeepEqual(res.Node, tt.wantRes.Node) {
  735. t.Errorf("#%d: Node=%v, expected %v", i, res.Node, tt.wantRes.Node)
  736. }
  737. }
  738. }
  739. func TestUnmarshalFailedKeysResponse(t *testing.T) {
  740. body := []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`)
  741. wantErr := Error{
  742. Code: 100,
  743. Message: "Key not found",
  744. Cause: "/foo",
  745. Index: uint64(18),
  746. }
  747. gotErr := unmarshalFailedKeysResponse(body)
  748. if !reflect.DeepEqual(wantErr, gotErr) {
  749. t.Errorf("unexpected error: want=%#v got=%#v", wantErr, gotErr)
  750. }
  751. }
  752. func TestUnmarshalFailedKeysResponseBadJSON(t *testing.T) {
  753. err := unmarshalFailedKeysResponse([]byte(`{"er`))
  754. if err == nil {
  755. t.Errorf("got nil error")
  756. } else if _, ok := err.(Error); ok {
  757. t.Errorf("error is of incorrect type *Error: %#v", err)
  758. }
  759. }
  760. func TestHTTPWatcherNextWaitAction(t *testing.T) {
  761. initAction := waitAction{
  762. Prefix: "/pants",
  763. Key: "/foo/bar",
  764. Recursive: true,
  765. WaitIndex: 19,
  766. }
  767. client := &actionAssertingHTTPClient{
  768. t: t,
  769. act: &initAction,
  770. resp: http.Response{
  771. StatusCode: http.StatusOK,
  772. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  773. },
  774. 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}}`),
  775. }
  776. wantResponse := &Response{
  777. Action: "update",
  778. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(21)},
  779. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  780. Index: uint64(42),
  781. }
  782. wantNextWait := waitAction{
  783. Prefix: "/pants",
  784. Key: "/foo/bar",
  785. Recursive: true,
  786. WaitIndex: 22,
  787. }
  788. watcher := &httpWatcher{
  789. client: client,
  790. nextWait: initAction,
  791. }
  792. resp, err := watcher.Next(context.Background())
  793. if err != nil {
  794. t.Errorf("non-nil error: %#v", err)
  795. }
  796. if !reflect.DeepEqual(wantResponse, resp) {
  797. t.Errorf("received incorrect Response: want=%#v got=%#v", wantResponse, resp)
  798. }
  799. if !reflect.DeepEqual(wantNextWait, watcher.nextWait) {
  800. t.Errorf("nextWait incorrect: want=%#v got=%#v", wantNextWait, watcher.nextWait)
  801. }
  802. }
  803. func TestHTTPWatcherNextFail(t *testing.T) {
  804. tests := []httpClient{
  805. // generic HTTP client failure
  806. &staticHTTPClient{
  807. err: errors.New("fail!"),
  808. },
  809. // unusable status code
  810. &staticHTTPClient{
  811. resp: http.Response{
  812. StatusCode: http.StatusTeapot,
  813. },
  814. },
  815. // etcd Error response
  816. &staticHTTPClient{
  817. resp: http.Response{
  818. StatusCode: http.StatusNotFound,
  819. },
  820. body: []byte(`{"errorCode":100,"message":"Key not found","cause":"/foo","index":18}`),
  821. },
  822. }
  823. for i, tt := range tests {
  824. act := waitAction{
  825. Prefix: "/pants",
  826. Key: "/foo/bar",
  827. Recursive: true,
  828. WaitIndex: 19,
  829. }
  830. watcher := &httpWatcher{
  831. client: tt,
  832. nextWait: act,
  833. }
  834. resp, err := watcher.Next(context.Background())
  835. if err == nil {
  836. t.Errorf("#%d: expected non-nil error", i)
  837. }
  838. if resp != nil {
  839. t.Errorf("#%d: expected nil Response, got %#v", i, resp)
  840. }
  841. if !reflect.DeepEqual(act, watcher.nextWait) {
  842. t.Errorf("#%d: nextWait changed: want=%#v got=%#v", i, act, watcher.nextWait)
  843. }
  844. }
  845. }
  846. func TestHTTPKeysAPIWatcherAction(t *testing.T) {
  847. tests := []struct {
  848. key string
  849. opts *WatcherOptions
  850. want waitAction
  851. }{
  852. {
  853. key: "/foo",
  854. opts: nil,
  855. want: waitAction{
  856. Key: "/foo",
  857. Recursive: false,
  858. WaitIndex: 0,
  859. },
  860. },
  861. {
  862. key: "/foo",
  863. opts: &WatcherOptions{
  864. Recursive: false,
  865. AfterIndex: 0,
  866. },
  867. want: waitAction{
  868. Key: "/foo",
  869. Recursive: false,
  870. WaitIndex: 0,
  871. },
  872. },
  873. {
  874. key: "/foo",
  875. opts: &WatcherOptions{
  876. Recursive: true,
  877. AfterIndex: 0,
  878. },
  879. want: waitAction{
  880. Key: "/foo",
  881. Recursive: true,
  882. WaitIndex: 0,
  883. },
  884. },
  885. {
  886. key: "/foo",
  887. opts: &WatcherOptions{
  888. Recursive: false,
  889. AfterIndex: 19,
  890. },
  891. want: waitAction{
  892. Key: "/foo",
  893. Recursive: false,
  894. WaitIndex: 20,
  895. },
  896. },
  897. }
  898. for i, tt := range tests {
  899. kAPI := &httpKeysAPI{
  900. client: &staticHTTPClient{err: errors.New("fail!")},
  901. }
  902. want := &httpWatcher{
  903. client: &staticHTTPClient{err: errors.New("fail!")},
  904. nextWait: tt.want,
  905. }
  906. got := kAPI.Watcher(tt.key, tt.opts)
  907. if !reflect.DeepEqual(want, got) {
  908. t.Errorf("#%d: incorrect watcher: want=%#v got=%#v", i, want, got)
  909. }
  910. }
  911. }
  912. func TestHTTPKeysAPISetAction(t *testing.T) {
  913. tests := []struct {
  914. key string
  915. value string
  916. opts *SetOptions
  917. wantAction httpAction
  918. }{
  919. // nil SetOptions
  920. {
  921. key: "/foo",
  922. value: "bar",
  923. opts: nil,
  924. wantAction: &setAction{
  925. Key: "/foo",
  926. Value: "bar",
  927. PrevValue: "",
  928. PrevIndex: 0,
  929. PrevExist: PrevIgnore,
  930. TTL: 0,
  931. },
  932. },
  933. // empty SetOptions
  934. {
  935. key: "/foo",
  936. value: "bar",
  937. opts: &SetOptions{},
  938. wantAction: &setAction{
  939. Key: "/foo",
  940. Value: "bar",
  941. PrevValue: "",
  942. PrevIndex: 0,
  943. PrevExist: PrevIgnore,
  944. TTL: 0,
  945. },
  946. },
  947. // populated SetOptions
  948. {
  949. key: "/foo",
  950. value: "bar",
  951. opts: &SetOptions{
  952. PrevValue: "baz",
  953. PrevIndex: 13,
  954. PrevExist: PrevExist,
  955. TTL: time.Minute,
  956. Dir: true,
  957. },
  958. wantAction: &setAction{
  959. Key: "/foo",
  960. Value: "bar",
  961. PrevValue: "baz",
  962. PrevIndex: 13,
  963. PrevExist: PrevExist,
  964. TTL: time.Minute,
  965. Dir: true,
  966. },
  967. },
  968. }
  969. for i, tt := range tests {
  970. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  971. kAPI := httpKeysAPI{client: client}
  972. kAPI.Set(context.Background(), tt.key, tt.value, tt.opts)
  973. }
  974. }
  975. func TestHTTPKeysAPISetError(t *testing.T) {
  976. tests := []httpClient{
  977. // generic HTTP client failure
  978. &staticHTTPClient{
  979. err: errors.New("fail!"),
  980. },
  981. // unusable status code
  982. &staticHTTPClient{
  983. resp: http.Response{
  984. StatusCode: http.StatusTeapot,
  985. },
  986. },
  987. // etcd Error response
  988. &staticHTTPClient{
  989. resp: http.Response{
  990. StatusCode: http.StatusInternalServerError,
  991. },
  992. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  993. },
  994. }
  995. for i, tt := range tests {
  996. kAPI := httpKeysAPI{client: tt}
  997. resp, err := kAPI.Set(context.Background(), "/foo", "bar", nil)
  998. if err == nil {
  999. t.Errorf("#%d: received nil error", i)
  1000. }
  1001. if resp != nil {
  1002. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1003. }
  1004. }
  1005. }
  1006. func TestHTTPKeysAPISetResponse(t *testing.T) {
  1007. client := &staticHTTPClient{
  1008. resp: http.Response{
  1009. StatusCode: http.StatusOK,
  1010. Header: http.Header{"X-Etcd-Index": []string{"21"}},
  1011. },
  1012. 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}}`),
  1013. }
  1014. wantResponse := &Response{
  1015. Action: "set",
  1016. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(21), ModifiedIndex: uint64(21)},
  1017. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1018. Index: uint64(21),
  1019. }
  1020. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1021. resp, err := kAPI.Set(context.Background(), "/foo/bar/baz", "snarf", nil)
  1022. if err != nil {
  1023. t.Errorf("non-nil error: %#v", err)
  1024. }
  1025. if !reflect.DeepEqual(wantResponse, resp) {
  1026. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1027. }
  1028. }
  1029. func TestHTTPKeysAPIGetAction(t *testing.T) {
  1030. tests := []struct {
  1031. key string
  1032. opts *GetOptions
  1033. wantAction httpAction
  1034. }{
  1035. // nil GetOptions
  1036. {
  1037. key: "/foo",
  1038. opts: nil,
  1039. wantAction: &getAction{
  1040. Key: "/foo",
  1041. Sorted: false,
  1042. Recursive: false,
  1043. },
  1044. },
  1045. // empty GetOptions
  1046. {
  1047. key: "/foo",
  1048. opts: &GetOptions{},
  1049. wantAction: &getAction{
  1050. Key: "/foo",
  1051. Sorted: false,
  1052. Recursive: false,
  1053. },
  1054. },
  1055. // populated GetOptions
  1056. {
  1057. key: "/foo",
  1058. opts: &GetOptions{
  1059. Sort: true,
  1060. Recursive: true,
  1061. Quorum: true,
  1062. },
  1063. wantAction: &getAction{
  1064. Key: "/foo",
  1065. Sorted: true,
  1066. Recursive: true,
  1067. Quorum: true,
  1068. },
  1069. },
  1070. }
  1071. for i, tt := range tests {
  1072. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1073. kAPI := httpKeysAPI{client: client}
  1074. kAPI.Get(context.Background(), tt.key, tt.opts)
  1075. }
  1076. }
  1077. func TestHTTPKeysAPIGetError(t *testing.T) {
  1078. tests := []httpClient{
  1079. // generic HTTP client failure
  1080. &staticHTTPClient{
  1081. err: errors.New("fail!"),
  1082. },
  1083. // unusable status code
  1084. &staticHTTPClient{
  1085. resp: http.Response{
  1086. StatusCode: http.StatusTeapot,
  1087. },
  1088. },
  1089. // etcd Error response
  1090. &staticHTTPClient{
  1091. resp: http.Response{
  1092. StatusCode: http.StatusInternalServerError,
  1093. },
  1094. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1095. },
  1096. }
  1097. for i, tt := range tests {
  1098. kAPI := httpKeysAPI{client: tt}
  1099. resp, err := kAPI.Get(context.Background(), "/foo", nil)
  1100. if err == nil {
  1101. t.Errorf("#%d: received nil error", i)
  1102. }
  1103. if resp != nil {
  1104. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1105. }
  1106. }
  1107. }
  1108. func TestHTTPKeysAPIGetResponse(t *testing.T) {
  1109. client := &staticHTTPClient{
  1110. resp: http.Response{
  1111. StatusCode: http.StatusOK,
  1112. Header: http.Header{"X-Etcd-Index": []string{"42"}},
  1113. },
  1114. 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}]}}`),
  1115. }
  1116. wantResponse := &Response{
  1117. Action: "get",
  1118. Node: &Node{
  1119. Key: "/pants/foo/bar",
  1120. Nodes: []*Node{
  1121. {Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: 21, ModifiedIndex: 25},
  1122. },
  1123. CreatedIndex: uint64(19),
  1124. ModifiedIndex: uint64(25),
  1125. },
  1126. Index: uint64(42),
  1127. }
  1128. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1129. resp, err := kAPI.Get(context.Background(), "/foo/bar", &GetOptions{Recursive: true})
  1130. if err != nil {
  1131. t.Errorf("non-nil error: %#v", err)
  1132. }
  1133. if !reflect.DeepEqual(wantResponse, resp) {
  1134. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1135. }
  1136. }
  1137. func TestHTTPKeysAPIDeleteAction(t *testing.T) {
  1138. tests := []struct {
  1139. key string
  1140. opts *DeleteOptions
  1141. wantAction httpAction
  1142. }{
  1143. // nil DeleteOptions
  1144. {
  1145. key: "/foo",
  1146. opts: nil,
  1147. wantAction: &deleteAction{
  1148. Key: "/foo",
  1149. PrevValue: "",
  1150. PrevIndex: 0,
  1151. Recursive: false,
  1152. },
  1153. },
  1154. // empty DeleteOptions
  1155. {
  1156. key: "/foo",
  1157. opts: &DeleteOptions{},
  1158. wantAction: &deleteAction{
  1159. Key: "/foo",
  1160. PrevValue: "",
  1161. PrevIndex: 0,
  1162. Recursive: false,
  1163. },
  1164. },
  1165. // populated DeleteOptions
  1166. {
  1167. key: "/foo",
  1168. opts: &DeleteOptions{
  1169. PrevValue: "baz",
  1170. PrevIndex: 13,
  1171. Recursive: true,
  1172. },
  1173. wantAction: &deleteAction{
  1174. Key: "/foo",
  1175. PrevValue: "baz",
  1176. PrevIndex: 13,
  1177. Recursive: true,
  1178. },
  1179. },
  1180. }
  1181. for i, tt := range tests {
  1182. client := &actionAssertingHTTPClient{t: t, num: i, act: tt.wantAction}
  1183. kAPI := httpKeysAPI{client: client}
  1184. kAPI.Delete(context.Background(), tt.key, tt.opts)
  1185. }
  1186. }
  1187. func TestHTTPKeysAPIDeleteError(t *testing.T) {
  1188. tests := []httpClient{
  1189. // generic HTTP client failure
  1190. &staticHTTPClient{
  1191. err: errors.New("fail!"),
  1192. },
  1193. // unusable status code
  1194. &staticHTTPClient{
  1195. resp: http.Response{
  1196. StatusCode: http.StatusTeapot,
  1197. },
  1198. },
  1199. // etcd Error response
  1200. &staticHTTPClient{
  1201. resp: http.Response{
  1202. StatusCode: http.StatusInternalServerError,
  1203. },
  1204. body: []byte(`{"errorCode":300,"message":"Raft internal error","cause":"/foo","index":18}`),
  1205. },
  1206. }
  1207. for i, tt := range tests {
  1208. kAPI := httpKeysAPI{client: tt}
  1209. resp, err := kAPI.Delete(context.Background(), "/foo", nil)
  1210. if err == nil {
  1211. t.Errorf("#%d: received nil error", i)
  1212. }
  1213. if resp != nil {
  1214. t.Errorf("#%d: received non-nil Response: %#v", i, resp)
  1215. }
  1216. }
  1217. }
  1218. func TestHTTPKeysAPIDeleteResponse(t *testing.T) {
  1219. client := &staticHTTPClient{
  1220. resp: http.Response{
  1221. StatusCode: http.StatusOK,
  1222. Header: http.Header{"X-Etcd-Index": []string{"22"}},
  1223. },
  1224. 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}}`),
  1225. }
  1226. wantResponse := &Response{
  1227. Action: "delete",
  1228. Node: &Node{Key: "/pants/foo/bar/baz", Value: "snarf", CreatedIndex: uint64(19), ModifiedIndex: uint64(22)},
  1229. PrevNode: &Node{Key: "/pants/foo/bar/baz", Value: "snazz", CreatedIndex: uint64(19), ModifiedIndex: uint64(20)},
  1230. Index: uint64(22),
  1231. }
  1232. kAPI := &httpKeysAPI{client: client, prefix: "/pants"}
  1233. resp, err := kAPI.Delete(context.Background(), "/foo/bar/baz", nil)
  1234. if err != nil {
  1235. t.Errorf("non-nil error: %#v", err)
  1236. }
  1237. if !reflect.DeepEqual(wantResponse, resp) {
  1238. t.Errorf("incorrect Response: want=%#v got=%#v", wantResponse, resp)
  1239. }
  1240. }
  1241. func TestHTTPKeysAPICreateAction(t *testing.T) {
  1242. act := &setAction{
  1243. Key: "/foo",
  1244. Value: "bar",
  1245. PrevExist: PrevNoExist,
  1246. PrevIndex: 0,
  1247. PrevValue: "",
  1248. TTL: 0,
  1249. }
  1250. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1251. kAPI.Create(context.Background(), "/foo", "bar")
  1252. }
  1253. func TestHTTPKeysAPICreateInOrderAction(t *testing.T) {
  1254. act := &createInOrderAction{
  1255. Dir: "/foo",
  1256. Value: "bar",
  1257. TTL: 0,
  1258. }
  1259. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1260. kAPI.CreateInOrder(context.Background(), "/foo", "bar", nil)
  1261. }
  1262. func TestHTTPKeysAPIUpdateAction(t *testing.T) {
  1263. act := &setAction{
  1264. Key: "/foo",
  1265. Value: "bar",
  1266. PrevExist: PrevExist,
  1267. PrevIndex: 0,
  1268. PrevValue: "",
  1269. TTL: 0,
  1270. }
  1271. kAPI := httpKeysAPI{client: &actionAssertingHTTPClient{t: t, act: act}}
  1272. kAPI.Update(context.Background(), "/foo", "bar")
  1273. }
  1274. func TestNodeTTLDuration(t *testing.T) {
  1275. tests := []struct {
  1276. node *Node
  1277. want time.Duration
  1278. }{
  1279. {
  1280. node: &Node{TTL: 0},
  1281. want: 0,
  1282. },
  1283. {
  1284. node: &Node{TTL: 97},
  1285. want: 97 * time.Second,
  1286. },
  1287. }
  1288. for i, tt := range tests {
  1289. got := tt.node.TTLDuration()
  1290. if tt.want != got {
  1291. t.Errorf("#%d: incorrect duration: want=%v got=%v", i, tt.want, got)
  1292. }
  1293. }
  1294. }