env.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. // import CloudBase from '@cloudbase/manager-node'
  2. import tcb from '../../src/index'
  3. import assert from 'assert'
  4. import config from '../config.local'
  5. import url from 'url'
  6. function setEnvValue() {
  7. process.env.TENCENTCLOUD_RUNENV = 'SCF'
  8. process.env._SCF_TCB_LOG = '1'
  9. process.env.TCB_ENV = 'MOCK_TCB_ENV'
  10. process.env.SCF_NAMESPACE = 'MOCK_SCF_NAMESPACE'
  11. process.env.TCB_SEQID = 'MOCK_TCB_SEQID'
  12. process.env.TENCENTCLOUD_SECRETID = 'MOCK_TENCENTCLOUD_SECRETID'
  13. process.env.TENCENTCLOUD_SECRETKEY = 'MOCK_TENCENTCLOUD_SECRETKEY'
  14. process.env.TENCENTCLOUD_SESSIONTOKEN = 'MOCK_TENCENTCLOUD_SESSIONTOKEN'
  15. process.env.TCB_SOURCE = 'MOCK_TCB_SOURCE'
  16. process.env.TCB_CONTEXT_KEYS = 'TCB_ENV,TCB_SEQID,TCB_SOURCE'
  17. process.env.TCB_CONTEXT_CNFG = ''
  18. }
  19. function resetEnvValue() {
  20. process.env.TENCENTCLOUD_RUNENV = ''
  21. process.env._SCF_TCB_LOG = ''
  22. process.env.TCB_ENV = ''
  23. process.env.SCF_NAMESPACE = ''
  24. process.env.TCB_SEQID = ''
  25. process.env.TENCENTCLOUD_SECRETID = ''
  26. process.env.TENCENTCLOUD_SECRETKEY = ''
  27. process.env.TENCENTCLOUD_SESSIONTOKEN = ''
  28. process.env.TCB_SOURCE = ''
  29. process.env.TCB_CONTEXT_KEYS = 'TCB_ENV,TCB_SEQID,TCB_SOURCE'
  30. process.env.TCB_CONTEXT_CNFG = ''
  31. }
  32. beforeEach(async () => {
  33. jest.resetModules()
  34. jest.resetAllMocks()
  35. })
  36. describe('mock 云函数环境', () => {
  37. it('验证 symbol', async () => {
  38. let newConfig = {
  39. ...config,
  40. env: tcb.SYMBOL_CURRENT_ENV
  41. }
  42. const app = tcb.init(newConfig)
  43. const testEnv = 'luke-prepay-test-8fjmkkf8fd6814b'
  44. // const testEnv = ''
  45. process.env.TCB_CONTEXT_KEYS = 'TCB_ENV' // 模拟云函数内keys变量
  46. process.env.TCB_ENV = testEnv
  47. const res = await app.callFunction({
  48. name: 'testTCBENV',
  49. data: { a: 1 }
  50. })
  51. console.log('res:', res)
  52. // console.log(res)
  53. assert(res.result === testEnv)
  54. })
  55. it('验证 TCB_CONTEXT_CNFG', async () => {
  56. jest.mock('../../src/utils/request', () => {
  57. return {
  58. extraRequest: jest.fn().mockImplementation(opts => {
  59. return Promise.resolve({
  60. statusCode: 200,
  61. body: {
  62. data: { response_data: opts },
  63. requestId: 'testRequestId'
  64. }
  65. })
  66. })
  67. }
  68. })
  69. setEnvValue()
  70. process.env.TCB_CONTEXT_CNFG = JSON.stringify({ URL: 'https://testurl' })
  71. const tcb = require('../../src/index')
  72. const app = tcb.init(config)
  73. // mock一次http请求
  74. let mockReqRes = await app.callFunction({
  75. name: 'unexistFunction',
  76. data: { a: 1 }
  77. })
  78. let reqOpts = mockReqRes.result
  79. const myURL = url.parse(reqOpts.url)
  80. assert(myURL.hostname === 'testurl')
  81. resetEnvValue()
  82. })
  83. it('验证 init环境变量 请求时未取到值', async () => {
  84. process.env.TCB_ENV = ''
  85. let newConfig = {
  86. ...config,
  87. env: tcb.SYMBOL_CURRENT_ENV
  88. }
  89. const app = tcb.init(newConfig)
  90. try {
  91. await app.callFunction({
  92. name: 'testTCBENV',
  93. data: { a: 1 }
  94. })
  95. } catch (e) {
  96. // console.log(e)
  97. assert(e.code === 'INVALID_PARAM')
  98. }
  99. newConfig = {
  100. ...newConfig,
  101. throwOnCode: false
  102. }
  103. const app1 = tcb.init(newConfig)
  104. const res = await app1.callFunction({
  105. name: 'testTCBENV',
  106. data: { a: 1 }
  107. })
  108. assert(res.code === 'INVALID_PARAM')
  109. })
  110. it('注入mock 云函数环境变量', async () => {
  111. setEnvValue()
  112. // 验证环境变量相关逻辑
  113. let app = tcb.init(config)
  114. // 1. _SCF_TCB_LOG(日志)
  115. assert(process.env._SCF_TCB_LOG == '1' && app.logger().isSupportClsReport == false)
  116. app.logger().log({ a: 1 })
  117. // mock support
  118. ;(<any>console).__baseLog__ = console.log
  119. app = tcb.init(config)
  120. assert(process.env._SCF_TCB_LOG == '1' && app.logger().isSupportClsReport === true)
  121. app.logger().log({ a: 1 })
  122. app.logger().info({ a: 1 })
  123. app.logger().error({ a: 1 })
  124. app.logger().warn({ a: 1 })
  125. // 2. TENCENTCLOUD_SECRETID TENCENTCLOUD_SECRETKEY TENCENTCLOUD_SESSIONTOKEN TENCENTCLOUD_RUNENV
  126. jest.mock('../../src/utils/request', () => {
  127. return {
  128. extraRequest: jest.fn().mockImplementation(opts => {
  129. let mockRes = null
  130. if (opts.body.action === 'functions.invokeFunction') {
  131. mockRes = {
  132. statusCode: 200,
  133. body: {
  134. data: { response_data: opts },
  135. requestId: 'testRequestId'
  136. }
  137. }
  138. }
  139. if (opts.body.action === 'database.getDocument') {
  140. mockRes = {
  141. statusCode: 200,
  142. body: {
  143. data: { data: { list: [opts] } },
  144. requestId: 'testRequestId'
  145. }
  146. }
  147. }
  148. return Promise.resolve(mockRes)
  149. })
  150. }
  151. })
  152. const tcb1 = require('../../src/index')
  153. const app1 = tcb1.init({ env: tcb1.SYMBOL_CURRENT_ENV })
  154. const appWithNoEnv = tcb1.init()
  155. let result = await app1.callFunction({
  156. name: 'test',
  157. data: { a: 1 }
  158. })
  159. let result1 = await appWithNoEnv.callFunction({
  160. name: 'test',
  161. data: { a: 1 }
  162. })
  163. const checkRes = result.result
  164. const checkRes1 = result1.result
  165. // scf url
  166. assert(
  167. checkRes.url.indexOf('http://MOCK_TCB_ENV.internal.tcb-api.tencentcloudapi.com') === 0
  168. )
  169. // tcb-source
  170. assert(checkRes.headers['x-tcb-source'].indexOf('MOCK_TCB_SOURCE') >= 0)
  171. // seqId
  172. assert(checkRes.url.indexOf('MOCK_TCB_SEQID') >= 0)
  173. // secretId
  174. // assert(checkRes.body.authorization.indexOf('MOCK_TENCENTCLOUD_SECRETID') >= 0)
  175. // sessionToken
  176. assert(checkRes.body.sessionToken === 'MOCK_TENCENTCLOUD_SESSIONTOKEN')
  177. // env
  178. assert(checkRes.body.envName === 'MOCK_TCB_ENV')
  179. // 验证不传env,请求参数中不含envName
  180. assert(checkRes1.body.envName === undefined)
  181. // 3. 验证env 设置 database(env) > init(env)
  182. const app2 = tcb1.init({ env: 'testEnv' })
  183. const db = app2.database({ env: 'testDbEnv' })
  184. let result2 = await app2.callFunction({
  185. name: 'test',
  186. data: { a: 1 }
  187. })
  188. // mock scf环境中无secretId或secretKey
  189. process.env.TENCENTCLOUD_SECRETID = ''
  190. const app4 = tcb.init()
  191. try {
  192. await app4.callFunction({
  193. name: 'test',
  194. data: { a: 1 }
  195. })
  196. } catch (err) {
  197. assert(
  198. err.code === 'INVALID_PARAM' &&
  199. err.message === 'missing authoration key, redeploy the function'
  200. )
  201. }
  202. resetEnvValue()
  203. })
  204. it('模拟注入环境密钥', async () => {
  205. process.env.TENCENTCLOUD_SECRETID = config.secretId
  206. process.env.TENCENTCLOUD_SECRETKEY = config.secretKey
  207. //
  208. const app = tcb.init({
  209. env: config.env
  210. })
  211. let result = await app.callFunction({
  212. name: 'test',
  213. data: { a: 1 }
  214. })
  215. delete process.env.TENCENTCLOUD_SECRETID
  216. delete process.env.TENCENTCLOUD_SECRETKEY
  217. assert(result.requestId)
  218. })
  219. })