Как передать конвейерные переменные из Visual Studio, используя C# - PullRequest
2 голосов
/ 25 февраля 2020

Я пытаюсь запустить несколько единичных тестов в Azure конвейере. Я передаю несколько параметров теста, используя настройки запуска теста в скрипте nunit, а также определил эти переменные в Pipleline. После теста мне нужно изменить переменную в конвейере Azure на основе результатов теста, которые можно использовать в последующих сценариях. Я пытался несколькими способами, но ничего не получается. Я попытался установить переменные конвейера в разделе Использование команд powershell в циклическом режиме, но он не работал, когда я пытался сделать то же самое из TestAssemblies (C# код).

код YAML

pool:
  name: New Agent Pool
  demands: vstest

variables:
  sauce: 'tomato'
  sauce1: 'something'

steps:
- task: NuGetCommand@2
  displayName: 'NuGet restore'
  inputs:
    restoreSolution: '$(Parameters.solution)'
  enabled: false

- task: VSBuild@1
  displayName: 'Build solution'
  inputs:
    solution: '$(Parameters.solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\\"'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'
  enabled: false

- powershell: |
   # Write your PowerShell commands here.

   Write-Output sauce = $(sauce)
   Write-Output sauce1 = $(sauce1)

  displayName: 'PowerShell Script'

- task: VSTest@2
  displayName: 'Test Assemblies'
  inputs:
    testAssemblyVer2: |
     **\$(BuildConfiguration)\*test*.dll
     !**\obj\**
    testFiltercriteria: 'Name=UnitTest1'
    runSettingsFile: SeleniumTest.ABC/Test.runsettings
    overrideTestrunParameters: '-sauce $(sauce)'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'

- powershell: |
   # Write your PowerShell commands here.

   Write-Output sauce = $(sauce)
   Write-Output sauce1 = $(sauce1)

  displayName: 'PowerShell Script'
    [Test]
    //[Category ("Google")]
    public void UnitTest1()
    {
        string sauce = TestContext.Parameters["sauce"];
        string sauce1 = TestContext.Parameters["sauce1"];
        TestContext.Progress.WriteLine(sauce);
        TestContext.Progress.WriteLine(sauce1);
        string text = "Write-Output '##vso[task.setvariable variable=sauce;isOutput=true]crushed tomatoes'";
        string op = RunScript(text);
        TestContext.WriteLine(op);
    }


    private string RunScript(string scriptText)
    {
        // create Powershell runspace
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        // create a pipeline and feed it the script text
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);

        Collection<PSObject> results = pipeline.Invoke();
        // close the runspace
        runspace.Close();

        // convert the script result into a single string
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }
        return stringBuilder.ToString();
    }

1 Ответ

2 голосов
/ 25 февраля 2020

Вы используете сложный способ печати сообщения посредством выполнения powershell. Вы можете использовать TestContext.Progress.WriteLine:

    [Test]
    public void Test1()
    {
        TestContext.Progress.WriteLine("##vso[task.setvariable variable=sauce]crushed tomatoes test project");
        Assert.Pass();
    }

Вот мой результат:

enter image description here

Дополнительно проверьте путь к своим тестам. Если вы используете ядро ​​net, это может быть как:

- task: VSTest@2

  displayName: 'VsTest - testAssemblies'

  inputs:

    testAssemblyVer2: |
     **\$(BuildConfiguration)\netcoreapp3.1\YourTestLib.dll
     !**\obj\**

    platform: '$(BuildPlatform)'

    configuration: '$(BuildConfiguration)'
...