keys_test.go 31 KB

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