environment.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. package httpexpect
  2. import (
  3. "errors"
  4. "sort"
  5. "sync"
  6. "time"
  7. "github.com/gobwas/glob"
  8. )
  9. // Environment provides a container for arbitrary data shared between tests.
  10. //
  11. // Example:
  12. //
  13. // env := NewEnvironment(t)
  14. // env.Put("key", "value")
  15. // value := env.GetString("key")
  16. type Environment struct {
  17. mu sync.RWMutex
  18. chain *chain
  19. data map[string]interface{}
  20. }
  21. // NewEnvironment returns a new Environment.
  22. //
  23. // If reporter is nil, the function panics.
  24. //
  25. // Example:
  26. //
  27. // env := NewEnvironment(t)
  28. func NewEnvironment(reporter Reporter) *Environment {
  29. return newEnvironment(newChainWithDefaults("Environment()", reporter))
  30. }
  31. // NewEnvironmentC returns a new Environment with config.
  32. //
  33. // Requirements for config are same as for WithConfig function.
  34. //
  35. // Example:
  36. //
  37. // env := NewEnvironmentC(config)
  38. func NewEnvironmentC(config Config) *Environment {
  39. return newEnvironment(newChainWithConfig("Environment()", config.withDefaults()))
  40. }
  41. func newEnvironment(parent *chain) *Environment {
  42. return &Environment{
  43. chain: parent.clone(),
  44. data: make(map[string]interface{}),
  45. }
  46. }
  47. // Put saves the value with key in the environment.
  48. //
  49. // Example:
  50. //
  51. // env := NewEnvironment(t)
  52. // env.Put("key1", "str")
  53. // env.Put("key2", 123)
  54. func (e *Environment) Put(key string, value interface{}) {
  55. opChain := e.chain.enter("Put(%q)", key)
  56. defer opChain.leave()
  57. e.mu.Lock()
  58. defer e.mu.Unlock()
  59. e.data[key] = value
  60. }
  61. // Delete removes the value with key from the environment.
  62. //
  63. // Example:
  64. //
  65. // env := NewEnvironment(t)
  66. // env.Put("key1", "str")
  67. // env.Delete("key1")
  68. func (e *Environment) Delete(key string) {
  69. opChain := e.chain.enter("Delete(%q)", key)
  70. defer opChain.leave()
  71. e.mu.Lock()
  72. defer e.mu.Unlock()
  73. delete(e.data, key)
  74. }
  75. // Clear will delete all key value pairs from the environment
  76. //
  77. // Example:
  78. //
  79. // env := NewEnvironment(t)
  80. // env.Put("key1", 123)
  81. // env.Put("key2", 456)
  82. // env.Clear()
  83. func (e *Environment) Clear() {
  84. opChain := e.chain.enter("Clear()")
  85. defer opChain.leave()
  86. e.mu.Lock()
  87. defer e.mu.Unlock()
  88. e.data = make(map[string]interface{})
  89. }
  90. // Has returns true if value exists in the environment.
  91. //
  92. // Example:
  93. //
  94. // if env.Has("key1") {
  95. // ...
  96. // }
  97. func (e *Environment) Has(key string) bool {
  98. opChain := e.chain.enter("Has(%q)", key)
  99. defer opChain.leave()
  100. e.mu.RLock()
  101. defer e.mu.RUnlock()
  102. _, ok := e.data[key]
  103. return ok
  104. }
  105. // Get returns value stored in the environment.
  106. //
  107. // If value does not exist, reports failure and returns nil.
  108. //
  109. // Example:
  110. //
  111. // value1 := env.Get("key1").(string)
  112. // value2 := env.Get("key1").(int)
  113. func (e *Environment) Get(key string) interface{} {
  114. opChain := e.chain.enter("Get(%q)", key)
  115. defer opChain.leave()
  116. e.mu.RLock()
  117. defer e.mu.RUnlock()
  118. value, _ := envValue(opChain, e.data, key)
  119. return value
  120. }
  121. // GetBool returns value stored in the environment, casted to bool.
  122. //
  123. // If value does not exist, or is not bool, reports failure and returns false.
  124. //
  125. // Example:
  126. //
  127. // value := env.GetBool("key")
  128. func (e *Environment) GetBool(key string) bool {
  129. opChain := e.chain.enter("GetBool(%q)", key)
  130. defer opChain.leave()
  131. e.mu.RLock()
  132. defer e.mu.RUnlock()
  133. value, ok := envValue(opChain, e.data, key)
  134. if !ok {
  135. return false
  136. }
  137. casted, ok := value.(bool)
  138. if !ok {
  139. opChain.fail(AssertionFailure{
  140. Type: AssertType,
  141. Actual: &AssertionValue{value},
  142. Errors: []error{
  143. errors.New("expected: bool value"),
  144. },
  145. })
  146. return false
  147. }
  148. return casted
  149. }
  150. // GetInt returns value stored in the environment, casted to int64.
  151. //
  152. // If value does not exist, or is not signed or unsigned integer that can be
  153. // represented as int without overflow, reports failure and returns zero.
  154. //
  155. // Example:
  156. //
  157. // value := env.GetInt("key")
  158. func (e *Environment) GetInt(key string) int {
  159. opChain := e.chain.enter("GetInt(%q)", key)
  160. defer opChain.leave()
  161. e.mu.RLock()
  162. defer e.mu.RUnlock()
  163. value, ok := envValue(opChain, e.data, key)
  164. if !ok {
  165. return 0
  166. }
  167. var casted int
  168. const (
  169. intSize = 32 << (^uint(0) >> 63) // 32 or 64
  170. maxInt = 1<<(intSize-1) - 1
  171. minInt = -1 << (intSize - 1)
  172. )
  173. switch num := value.(type) {
  174. case int8:
  175. casted = int(num)
  176. ok = (int64(num) >= minInt) && (int64(num) <= maxInt)
  177. case int16:
  178. casted = int(num)
  179. ok = (int64(num) >= minInt) && (int64(num) <= maxInt)
  180. case int32:
  181. casted = int(num)
  182. ok = (int64(num) >= minInt) && (int64(num) <= maxInt)
  183. case int64:
  184. casted = int(num)
  185. ok = (int64(num) >= minInt) && (int64(num) <= maxInt)
  186. case int:
  187. casted = num
  188. ok = (int64(num) >= minInt) && (int64(num) <= maxInt)
  189. case uint8:
  190. casted = int(num)
  191. ok = (uint64(num) <= maxInt)
  192. case uint16:
  193. casted = int(num)
  194. ok = (uint64(num) <= maxInt)
  195. case uint32:
  196. casted = int(num)
  197. ok = (uint64(num) <= maxInt)
  198. case uint64:
  199. casted = int(num)
  200. ok = (uint64(num) <= maxInt)
  201. case uint:
  202. casted = int(num)
  203. ok = (uint64(num) <= maxInt)
  204. default:
  205. opChain.fail(AssertionFailure{
  206. Type: AssertType,
  207. Actual: &AssertionValue{value},
  208. Errors: []error{
  209. errors.New("expected: signed or unsigned integer"),
  210. },
  211. })
  212. return 0
  213. }
  214. if !ok {
  215. opChain.fail(AssertionFailure{
  216. Type: AssertInRange,
  217. Actual: &AssertionValue{value},
  218. Expected: &AssertionValue{AssertionRange{minInt, maxInt}},
  219. Errors: []error{
  220. errors.New(
  221. "expected: value can be represented as int without overflow"),
  222. },
  223. })
  224. return 0
  225. }
  226. return casted
  227. }
  228. // GetFloat returns value stored in the environment, casted to float64.
  229. //
  230. // If value does not exist, or is not floating point value, reports failure
  231. // and returns zero value.
  232. //
  233. // Example:
  234. //
  235. // value := env.GetFloat("key")
  236. func (e *Environment) GetFloat(key string) float64 {
  237. opChain := e.chain.enter("GetFloat(%q)", key)
  238. defer opChain.leave()
  239. e.mu.RLock()
  240. defer e.mu.RUnlock()
  241. value, ok := envValue(opChain, e.data, key)
  242. if !ok {
  243. return 0
  244. }
  245. var casted float64
  246. switch num := value.(type) {
  247. case float32:
  248. casted = float64(num)
  249. case float64:
  250. casted = num
  251. default:
  252. opChain.fail(AssertionFailure{
  253. Type: AssertType,
  254. Actual: &AssertionValue{value},
  255. Errors: []error{
  256. errors.New("expected: float32 or float64"),
  257. },
  258. })
  259. return 0
  260. }
  261. return casted
  262. }
  263. // GetString returns value stored in the environment, casted to string.
  264. //
  265. // If value does not exist, or is not string, reports failure and returns
  266. // empty string.
  267. //
  268. // Example:
  269. //
  270. // value := env.GetString("key")
  271. func (e *Environment) GetString(key string) string {
  272. opChain := e.chain.enter("GetString(%q)", key)
  273. defer opChain.leave()
  274. e.mu.RLock()
  275. defer e.mu.RUnlock()
  276. value, ok := envValue(opChain, e.data, key)
  277. if !ok {
  278. return ""
  279. }
  280. casted, ok := value.(string)
  281. if !ok {
  282. opChain.fail(AssertionFailure{
  283. Type: AssertType,
  284. Actual: &AssertionValue{value},
  285. Errors: []error{
  286. errors.New("expected: string value"),
  287. },
  288. })
  289. return ""
  290. }
  291. return casted
  292. }
  293. // GetBytes returns value stored in the environment, casted to []byte.
  294. //
  295. // If value does not exist, or is not []byte slice, reports failure and returns nil.
  296. //
  297. // Example:
  298. //
  299. // value := env.GetBytes("key")
  300. func (e *Environment) GetBytes(key string) []byte {
  301. opChain := e.chain.enter("GetBytes(%q)", key)
  302. defer opChain.leave()
  303. e.mu.RLock()
  304. defer e.mu.RUnlock()
  305. value, ok := envValue(opChain, e.data, key)
  306. if !ok {
  307. return nil
  308. }
  309. casted, ok := value.([]byte)
  310. if !ok {
  311. opChain.fail(AssertionFailure{
  312. Type: AssertType,
  313. Actual: &AssertionValue{value},
  314. Errors: []error{
  315. errors.New("expected: []byte slice"),
  316. },
  317. })
  318. return nil
  319. }
  320. return casted
  321. }
  322. // GetDuration returns value stored in the environment, casted to time.Duration.
  323. //
  324. // If value does not exist, is not time.Duration, reports failure and returns
  325. // zero duration.
  326. //
  327. // Example:
  328. //
  329. // value := env.GetDuration("key")
  330. func (e *Environment) GetDuration(key string) time.Duration {
  331. opChain := e.chain.enter("GetDuration(%q)", key)
  332. defer opChain.leave()
  333. e.mu.RLock()
  334. defer e.mu.RUnlock()
  335. value, ok := envValue(opChain, e.data, key)
  336. if !ok {
  337. return time.Duration(0)
  338. }
  339. casted, ok := value.(time.Duration)
  340. if !ok {
  341. opChain.fail(AssertionFailure{
  342. Type: AssertType,
  343. Actual: &AssertionValue{value},
  344. Errors: []error{
  345. errors.New("expected: time.Duration value"),
  346. },
  347. })
  348. return time.Duration(0)
  349. }
  350. return casted
  351. }
  352. // GetTime returns value stored in the environment, casted to time.Time.
  353. //
  354. // If value does not exist, is not time.Time, reports failure and returns
  355. // zero time.
  356. //
  357. // Example:
  358. //
  359. // value := env.GetTime("key")
  360. func (e *Environment) GetTime(key string) time.Time {
  361. opChain := e.chain.enter("GetTime(%q)", key)
  362. defer opChain.leave()
  363. e.mu.RLock()
  364. defer e.mu.RUnlock()
  365. value, ok := envValue(opChain, e.data, key)
  366. if !ok {
  367. return time.Unix(0, 0)
  368. }
  369. casted, ok := value.(time.Time)
  370. if !ok {
  371. opChain.fail(AssertionFailure{
  372. Type: AssertType,
  373. Actual: &AssertionValue{value},
  374. Errors: []error{
  375. errors.New("expected: time.Time value"),
  376. },
  377. })
  378. return time.Unix(0, 0)
  379. }
  380. return casted
  381. }
  382. // List returns a sorted slice of keys.
  383. //
  384. // Example:
  385. //
  386. // env := NewEnvironment(t)
  387. //
  388. // for _, key := range env.List() {
  389. // ...
  390. // }
  391. func (e *Environment) List() []string {
  392. opChain := e.chain.enter("List()")
  393. defer opChain.leave()
  394. e.mu.RLock()
  395. defer e.mu.RUnlock()
  396. keys := []string{}
  397. for key := range e.data {
  398. keys = append(keys, key)
  399. }
  400. sort.Slice(keys, func(i, j int) bool {
  401. return keys[i] < keys[j]
  402. })
  403. return keys
  404. }
  405. // Glob accepts a glob pattern and returns a sorted slice of
  406. // keys that match the pattern.
  407. //
  408. // If the pattern is invalid, reports failure and returns an
  409. // empty slice.
  410. //
  411. // Example:
  412. //
  413. // env := NewEnvironment(t)
  414. //
  415. // for _, key := range env.Glob("foo.*") {
  416. // ...
  417. // }
  418. func (e *Environment) Glob(pattern string) []string {
  419. opChain := e.chain.enter("Glob(%q)", pattern)
  420. defer opChain.leave()
  421. e.mu.RLock()
  422. defer e.mu.RUnlock()
  423. glb, err := glob.Compile(pattern)
  424. if err != nil {
  425. opChain.fail(AssertionFailure{
  426. Type: AssertUsage,
  427. Errors: []error{
  428. errors.New("unexpected invalid glob pattern"),
  429. },
  430. })
  431. return []string{}
  432. }
  433. keys := []string{}
  434. for key := range e.data {
  435. if glb.Match(key) {
  436. keys = append(keys, key)
  437. }
  438. }
  439. sort.Slice(keys, func(i, j int) bool {
  440. return keys[i] < keys[j]
  441. })
  442. return keys
  443. }
  444. func envValue(chain *chain, env map[string]interface{}, key string) (interface{}, bool) {
  445. v, ok := env[key]
  446. if !ok {
  447. chain.fail(AssertionFailure{
  448. Type: AssertContainsKey,
  449. Actual: &AssertionValue{env},
  450. Expected: &AssertionValue{key},
  451. Errors: []error{
  452. errors.New("expected: environment contains key"),
  453. },
  454. })
  455. return nil, false
  456. }
  457. return v, true
  458. }