Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TestFileSetup.cs « TestFileSetup « TestUtils « src « runtest « CoreFX « tests - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 50e89c5ad7667a78198c2b7a16c1e0f759a8960d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.CommandLine;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Schema.Generation;

namespace CoreFX.TestUtils.TestFileSetup
{
    /// <summary>
    /// Defines the set of flags that represent exit codes
    /// </summary>
    [Flags]
    public enum ExitCode : int
    {
        Success = 0,
        HttpError = 1,
        IOError = 2,
        JsonSchemaValidationError = 3,
        UnknownError = 10

    }

    /// <summary>
    /// This helper class is used to fetch CoreFX tests from a specified URL, unarchive them and create a flat directory structure
    /// through which to iterate.
    /// </summary>
    public static class TestFileSetup
    {
        private static HttpClient httpClient;
        private static bool cleanTestBuild = false;

        private static string outputDir;
        private static string testUrl;
        private static string testListPath;

        public static void Main(string[] args)
        {
            ExitCode exitCode = ExitCode.UnknownError;
            ArgumentSyntax argSyntax = ParseCommandLine(args);

            try
            {
                if (!Directory.Exists(outputDir))
                    Directory.CreateDirectory(outputDir);

                if (cleanTestBuild)
                {
                    CleanBuild(outputDir);
                }

                // Map test names to their definitions
                Dictionary<string, XUnitTestAssembly> testAssemblyDefinitions = DeserializeTestJson(testListPath);

                SetupTests(testUrl, outputDir, testAssemblyDefinitions).Wait();
                exitCode = ExitCode.Success;
            }

            catch (AggregateException e)
            {
                e.Handle(innerExc =>
                {

                    if (innerExc is HttpRequestException)
                    {
                        exitCode = ExitCode.HttpError;
                        Console.WriteLine("Error downloading tests from: " + testUrl);
                        Console.WriteLine(innerExc.Message);
                        return true;
                    }
                    else if (innerExc is IOException)
                    {
                        exitCode = ExitCode.IOError;
                        Console.WriteLine(innerExc.Message);
                        return true;
                    }
                    else if (innerExc is JSchemaValidationException || innerExc is JsonSerializationException)
                    {
                        exitCode = ExitCode.JsonSchemaValidationError;
                        Console.WriteLine("Error validating test list: ");
                        Console.WriteLine(innerExc.Message);
                        return true;
                    }
                    return false;
                });
            }

            Environment.Exit((int)exitCode);
        }

        private static ArgumentSyntax ParseCommandLine(string[] args)
        {
            ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.DefineOption("out|outDir|outputDirectory", ref outputDir, "Directory where tests are downloaded");
                syntax.DefineOption("testUrl", ref testUrl, "URL, pointing to the list of tests");
                syntax.DefineOption("testListJsonPath", ref testListPath, "JSON-formatted list of test assembly names to download");
                syntax.DefineOption("clean|cleanOutputDir", ref cleanTestBuild, "Clean test assembly output directory");
            });

            return argSyntax;
        }

        private static Dictionary<string, XUnitTestAssembly> DeserializeTestJson(string testDefinitionFilePath)
        {
            JSchemaGenerator jsonGenerator = new JSchemaGenerator();

            JSchema testDefinitionSchema = jsonGenerator.Generate(typeof(IList<XUnitTestAssembly>));
            IList<XUnitTestAssembly> testAssemblies = new List<XUnitTestAssembly>();

            IList<string> validationMessages = new List<string>();

            using (var sr = new StreamReader(testDefinitionFilePath))
            using (var jsonReader = new JsonTextReader(sr))
            using (var jsonValidationReader = new JSchemaValidatingReader(jsonReader))
            {
                // Create schema validator
                jsonValidationReader.Schema = testDefinitionSchema;
                jsonValidationReader.ValidationEventHandler += (o, a) => validationMessages.Add(a.Message);

                // Deserialize json test assembly definitions
                JsonSerializer serializer = new JsonSerializer();
                try
                {
                    testAssemblies = serializer.Deserialize<List<XUnitTestAssembly>>(jsonValidationReader);
                }
                catch (JsonSerializationException ex)
                {
                    throw new AggregateException(ex);
                }
            }

            // TODO - ABORT AND WARN
            if (validationMessages.Count != 0)
            {
                StringBuilder aggregateExceptionMessage = new StringBuilder();
                foreach (string validationMessage in validationMessages)
                {
                    aggregateExceptionMessage.Append("JSON Validation Error: ");
                    aggregateExceptionMessage.Append(validationMessage);
                    aggregateExceptionMessage.AppendLine();
                }

                throw new AggregateException(new JSchemaValidationException(aggregateExceptionMessage.ToString()));

            }

            var nameToTestAssemblyDef = new Dictionary<string, XUnitTestAssembly>();

            // Map test names to their definitions
            foreach (XUnitTestAssembly assembly in testAssemblies)
            {
                nameToTestAssemblyDef.Add(assembly.Name, assembly);
            }

            return nameToTestAssemblyDef;
        }

        private static async Task SetupTests(string jsonUrl, string destinationDirectory, Dictionary<string, XUnitTestAssembly> testDefinitions = null, bool runAllTests = false)
        {
            Debug.Assert(Directory.Exists(destinationDirectory));
            Debug.Assert(runAllTests || testDefinitions != null);

            string tempDirPath = Path.Combine(destinationDirectory, "temp");
            if (!Directory.Exists(tempDirPath))
            {
                Directory.CreateDirectory(tempDirPath);
            }
            Dictionary<string, XUnitTestAssembly> testPayloads = await GetTestUrls(jsonUrl, testDefinitions, runAllTests);

            if (testPayloads == null)
            {
                return;
            }

            await GetTestArchives(testPayloads, tempDirPath);
            ExpandArchivesInDirectory(tempDirPath, destinationDirectory);

            RSPGenerator rspGenerator = new RSPGenerator();
            foreach (XUnitTestAssembly assembly in testDefinitions.Values)
            {
                rspGenerator.GenerateRSPFile(assembly, Path.Combine(destinationDirectory, assembly.Name));
            }

            Directory.Delete(tempDirPath);
        }

        private static async Task<Dictionary<string, XUnitTestAssembly>> GetTestUrls(string jsonUrl, Dictionary<string, XUnitTestAssembly> testDefinitions = null, bool runAllTests = false)
        {
            if (httpClient is null)
            {
                httpClient = new HttpClient();
            }

            Debug.Assert(runAllTests || testDefinitions != null);
            // Set up the json stream reader
            using (var responseStream = await httpClient.GetStreamAsync(jsonUrl))
            using (var streamReader = new StreamReader(responseStream))
            using (var jsonReader = new JsonTextReader(streamReader))
            {
                // Manual parsing - we only need to key-value pairs from each object and this avoids deserializing all of the work items into objects
                string markedTestName = string.Empty;
                string currentPropertyName = string.Empty;

                while (jsonReader.Read())
                {
                    if (jsonReader.Value != null)
                    {
                        switch (jsonReader.TokenType)
                        {
                            case JsonToken.PropertyName:
                                currentPropertyName = jsonReader.Value.ToString();
                                break;
                            case JsonToken.String:
                                if (currentPropertyName.Equals("WorkItemId"))
                                {
                                    string currentTestName = jsonReader.Value.ToString();

                                    if (runAllTests || testDefinitions.ContainsKey(currentTestName))
                                    {
                                        markedTestName = currentTestName;
                                    }
                                }
                                else if (currentPropertyName.Equals("PayloadUri") && markedTestName != string.Empty)
                                {
                                    if (!testDefinitions.ContainsKey(markedTestName))
                                    {
                                        testDefinitions[markedTestName] = new XUnitTestAssembly() { Name = markedTestName };
                                    }
                                    testDefinitions[markedTestName].Url = jsonReader.Value.ToString();
                                    markedTestName = string.Empty;
                                }
                                break;
                        }
                    }
                }

            }
            return testDefinitions;
        }

        private static async Task GetTestArchives(Dictionary<string, XUnitTestAssembly> testPayloads, string downloadDir)
        {
            if (httpClient is null)
            {
                httpClient = new HttpClient();
            }

            foreach (string testName in testPayloads.Keys)
            {
                string payloadUri = testPayloads[testName].Url;

                if (!Uri.IsWellFormedUriString(payloadUri, UriKind.Absolute))
                    continue;

                using (var response = await httpClient.GetStreamAsync(payloadUri))
                {
                    if (response.CanRead)
                    {
                        // Create the test setup directory if it doesn't exist
                        if (!Directory.Exists(downloadDir))
                        {
                            Directory.CreateDirectory(downloadDir);
                        }

                        // CoreFX test archives are output as .zip regardless of platform
                        string archivePath = Path.Combine(downloadDir, testName + ".zip");

                        // Copy to a temp folder 
                        using (FileStream file = new FileStream(archivePath, FileMode.Create))
                        {
                            await response.CopyToAsync(file);
                        }

                    }
                }
            }
        }

        private static void ExpandArchivesInDirectory(string archiveDirectory, string destinationDirectory, bool cleanup = true)
        {
            Debug.Assert(Directory.Exists(archiveDirectory));
            Debug.Assert(Directory.Exists(destinationDirectory));

            string[] archives = Directory.GetFiles(archiveDirectory, "*.zip", SearchOption.TopDirectoryOnly);

            foreach (string archivePath in archives)
            {
                string destinationDirName = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(archivePath));

                ZipFile.ExtractToDirectory(archivePath, destinationDirName);


                // Delete archives
                if (cleanup)
                {
                    File.Delete(archivePath);
                }
            }
        }

        private static void CleanBuild(string directoryToClean)
        {
            Debug.Assert(Directory.Exists(directoryToClean));
            DirectoryInfo dirInfo = new DirectoryInfo(directoryToClean);

            foreach (FileInfo file in dirInfo.EnumerateFiles())
            {
                file.Delete();
            }

            foreach (DirectoryInfo dir in dirInfo.EnumerateDirectories())
            {
                dir.Delete(true);
            }
        }

    }
}