如何在pytest测试中获取秘密



假设我有一个带有一些测试函数的pytest模块。为了运行测试,测试函数需要有一个个人访问令牌。我想在Azure DevOps中的CI流程中运行这些测试。我可以将PAT作为一个秘密变量存储在Pipeline定义中,但问题是,在运行pytest时,如何将这个秘密传递给测试函数?

编辑

我可以从文件中读取,在运行pytest之前,我可以格式化这个文件,但我不太喜欢这种方法。

有什么建议吗?

我假设你有一个管道,但下面是你可以做到的。

首先在你想要的钥匙库中创建你的秘密。我使用Python和Azure sdk创建了一个应用程序,它可以让你非常容易地在密钥库中创建多个秘密-https://github.com/TechyTish/AzurePy/blob/main/create-azure-secrets-README.md

假设您的机密存储为(secretNamesecretValue(:

  • 示例1:1234
  • 示例2:hello567

。。。etc

#filename: example.json
"SOME_KEY_NAME1": "{#exampleOne#}",
"SOME_KEY_NAME2": "{#exampleTwo#}",

创建一个将有两个任务的YAML管道:

  1. 提取密钥库机密
  2. 用secret替换.json键值
#filename: azure-pipeline.yml
# Azure Key Vault
# Download Azure Key Vault secrets
- task: AzureKeyVault@2
inputs:
connectedServiceName: # Azure subscription - you will need to create an service connection in the repo which has access policies to the keyvault
keyVaultName: # Name of existing key vault
secretsFilter: '*' # Downloads all secrets for the key vault
runAsPreJob: true # Runs before the job starts

在上一个任务下面添加另一个任务。这将在.json文件中查找任何带有{#预修复和#}后缀的键值,并且此任务之后的变量(如下(将用您分配给它的机密值替换.json文件中的值。

#filename: azure-pipeline.yml
- task: qetza.replacetokens.replacetokens-task.replacetokens@3
inputs:
targetFiles: "$(Pipeline.Workspace)/codepath/jsonFileName.json"
encoding: "auto"
writeBOM: true
verbosity: "detailed"
actionOnMissing: "warn"
keepToken: false
tokenPrefix: "{#"
tokenSuffix: "#}"
displayName: Perform variable substitution in json file
- script: echo "$(<folderName/example.json)" #open json file in the terminal to show the changes
#.json value: point to secret name
variables:
exampleOne: $(example1)
exampleTwo: $(example2)
#....
#etc

运行管道(勾选调试框(,.json文件的输出应该是:

#filename: example.json
"SOME_KEY_NAME1": "1234",
"SOME_KEY_NAME2": "hello567"
#....
#etc

这样,只有当管道在您使用的任何主机代理(虚拟机(上运行时,您的秘密才会被泄露。

最新更新