env.test.ts 7.9 KB

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