void ITestService.TestFailedTestsOfTestcaseOfTestsuite(int testerId, int testsystemId, int testsuiteId, int testcaseId) { Testsuite testsuite = _testsuiteRepository.GetById(testsuiteId); Testcase testcase = testsuite.Testcases.Single(t => t.ID == testcaseId); IList <Result> errorResults = _resultRepository.GetErrorResultsOfTestsuite(testsystemId, testsuite.Browsers, new List <Testcase> { testcase }, testsuite.Languages); Testsystem testsystem = _testsystemRepository.GetById(testsystemId); Tester tester = _testerRepository.GetById(testerId); TestJob testjob = CreateTestJob("Repeat failed of " + "Testcase " + testcase.Name + "(Testsuite " + testsuite.Name + ")", testsuite, testsystem, tester); ITestJobManager testjobManager = new TestJobManager(testjob); ICollection <WorkItem> workItems = (from result in errorResults select new WorkItem(testjobManager) { Testcase = result.Testcase, Browser = result.Browser, Language = result.Language, Testsystem = testsystem, Tester = tester }).ToList(); _testPool.AddTestJob(testjobManager, workItems); }
void TestString(Testcase tc, string expected, NormalizationForm f) { string input = tc.Source; string actual = null; switch (f) { default: actual = Normalization.Normalize(input, 0); break; case NormalizationForm.FormD: actual = Normalization.Normalize(input, 1); break; case NormalizationForm.FormKC: actual = Normalization.Normalize(input, 2); break; case NormalizationForm.FormKD: actual = Normalization.Normalize(input, 3); break; } if (actual != expected) { Console.WriteLine("Error: expected {0} but was {1} (for {2},type{3} form {4})", expected, actual, tc.Source, tc.TestType, f); } }
public MainPage() { UpdateScreen = new DispatcherTimer(); DoPositioning = new DispatcherTimer(); RetrievePosition = new DispatcherTimer(); UpdateScreen.Tick += UpdateScreen_Tick; DoPositioning.Tick += DoPositioning_Tick; RetrievePosition.Tick += RetrievePosition_Tick; UpdateScreen.Interval = new TimeSpan(0, 0, 0, 0, 1000 / 50); RetrievePosition.Interval = new TimeSpan(0, 0, 0, 0, 200); DoPositioning.Interval = new TimeSpan(0, 0, 0, 0, 400); this.InitializeComponent(); StopRunning(); _Pozyx = new Pozyx(); _Testcase = new Testcase(_Pozyx); _FriendPosition = new Position(); //_FriendId = 0x6843; _FriendId = 0x6E38; // The id of our 2nd pozyx _UseFriend = true; StartUp(); }
public void TestValidConnectionString() { Testcase[] testcases = new Testcase[] { new Testcase() { ConnectionString = "ACCOUNT=testaccount;USER=testuser;PASSWORD=123;", ExpectedProperties = new SFSessionProperties() { { SFSessionProperty.ACCOUNT, "testaccount" }, { SFSessionProperty.USER, "testuser" }, { SFSessionProperty.HOST, "testaccount.snowflakecomputing.com" }, { SFSessionProperty.AUTHENTICATOR, "snowflake" }, { SFSessionProperty.SCHEME, "https" }, { SFSessionProperty.CONNECTION_TIMEOUT, "0" }, { SFSessionProperty.PASSWORD, "123" }, { SFSessionProperty.PORT, "443" }, { SFSessionProperty.VALIDATE_DEFAULT_PARAMETERS, "true" }, }, }, }; foreach (Testcase testcase in testcases) { testcase.TestValidCase(); } }
public static void __Test1() { string str = "Hello"; string str2 = "US"; string str3 = "Longer String Than Most"; Testcase.Test((str.Length == 5) && (str2.Length == 2) && (str3.Length == 23), "System.String", "Length test"); }
public void TestAddingTwoStepsReturnsSummaryWithNumeratedSteps() { var testcase = new Testcase(); testcase.AddSummaryStep("One step"); testcase.AddSummaryStep("Another step"); Assert.AreEqual("1. One step \r2. Another step \r", testcase.Summary); }
public void Update(Testcase id) { Testcase item = testcases.Find((i) => i.Id == id.Id); item.Title = id.Title; item.Module = id.Module; item.Author = id.Author; item.FinalStatus = id.FinalStatus; }
// GET: Testcase public ActionResult Details(int Id, string branch) { using (PnPTestAutomationEntities dc = new PnPTestAutomationEntities()) { Testcase TestResults = null; IEnumerable <Testcase> testResultSets = from testreultset in dc.TestResultSets join testrunset in dc.TestRunSets on testreultset.TestRunId equals testrunset.Id join configset in dc.TestConfigurationSets on testrunset.TestConfigurationId equals configset.Id where testreultset.Id == Id select new Testcase { AnonymousAccess = configset.AnonymousAccess, Outcome = testreultset.Outcome, Error = testreultset.ErrorMessage, StackTrace = testreultset.ErrorStackTrace, TestDuration = testreultset.Duration, TestCasename = testreultset.TestCaseName, Id = testreultset.Id, Testdate = testreultset.StartTime }; if (!Request.IsAuthenticated || !AuthorizationManager.IsCoreTeamMember(User)) { TestResults = testResultSets.Where(c => c.AnonymousAccess == true).SingleOrDefault(); } else { TestResults = testResultSets.SingleOrDefault(); } if (TestResults != null) { List <Testcase> testcaseConsoleOutput = (from resultmessage in dc.TestResultMessageSets where resultmessage.TestResultId == Id select new Testcase { ConsoleOutPut = resultmessage.Text }).ToList(); string consoleoutput = string.Empty; if (testcaseConsoleOutput != null && testcaseConsoleOutput.Any()) { foreach (Testcase consoleOutPutText in testcaseConsoleOutput) { consoleoutput += consoleOutPutText.ConsoleOutPut + "\n"; } } TestResults.ConsoleOutPut = consoleoutput; TestResults.Branch = String.Format(Constants.Constants.gitBranch, branch); } return(View(TestResults)); } }
public TestcaseToJudge(Testcase t) { testcaseid = t.TestcaseId; probid = t.ProblemId; md5sum_input = t.Md5sumInput; md5sum_output = t.Md5sumOutput; rank = t.Rank; probid = t.ProblemId; description_as_string = t.Description; }
public object CompleteClone() { QAliberTreeNode newNode = Clone() as QAliberTreeNode; newNode.Testcase = Testcase.Clone() as TestCase; UpdateTags(newNode, newNode.Testcase); newNode.NonHighlightForeColor = newNode.ForeColor = newNode.Testcase.Color; newNode.NonHighlightBackColor = newNode.BackColor = Color.White; return(newNode); }
protected override void Execute(NativeActivityContext context) { var name = TestcaseName.Get(context); var desc = TestcaseDescription.Get(context); var testcase = new Testcase(name, desc); if (Body != null) { context.ScheduleAction <Testcase>(Body, testcase, OnCompleted, OnFaulted); } }
public void TestPostTestResultSendsTestStatusAsInteger() { var inMemoryTestrailClient = new InMemoryTestrailClient(); var service = new TestrailService(inMemoryTestrailClient); var testcase = new Testcase { Status = Teststatus.Passed }; service.PostTestResult(testcase, 10); Assert.AreEqual(inMemoryTestrailClient.LastTestStatus, (int)Teststatus.Passed); }
public void TestcaseExecuteCreatesAndDisposesInstancesWhenNotIDisposable() { try { Testcase test = new Testcase(typeof(StubTestcase), "FakeTest"); test.Execute(); UnitTestAssert.IsTrue(StubTestcase.ctorCounter == 1); UnitTestAssert.IsTrue(StubTestcase.methodCounter == 1); UnitTestAssert.IsTrue(StubTestcase.disposeCounter == 0); } finally { StubTestcase.Reset(); } }
private static void MapOutputToResult(Testcase test, TestResultDrop drop) { var messages = new List <TestResultMessageDrop>(); var errorMessage = new StringBuilder(); var errorStackTrace = new StringBuilder(); if (test.FailureSpecified) { foreach (var failure in test.Failure) { if (!string.IsNullOrEmpty(failure.Message)) { errorMessage.Append(failure.Message); errorStackTrace.Append(string.Join(Environment.NewLine, failure.Text)); } } } if (test.System_OutSpecified) { foreach (var stdOut in test.System_Out) { if (!string.IsNullOrEmpty(stdOut)) { messages.Add(new TestResultMessageDrop { Text = stdOut, Category = "Standard" }); } } } if (test.System_OutSpecified) { foreach (var stdErr in test.System_Out) { if (!string.IsNullOrEmpty(stdErr)) { messages.Add(new TestResultMessageDrop { Text = stdErr, Category = "Error" }); } } } drop.Messages = messages; drop.ErrorMessage = errorMessage.ToString(); drop.ErrorStackTrace = errorStackTrace.ToString(); }
public static TestcaseBlockerDataset GenerateRandomData(int numberOfBlockers, int numberOfTestcases) { var blockers = new List <Blocker>(); var testcases = new List <Testcase>(); var rnd = new Random(); // Generate Blockers for (int i = 1; i <= numberOfBlockers; i++) { blockers.Add(new Blocker { Id = Guid.NewGuid().ToString(), Name = $"Blocker {i}" }); } // Generate Testcases for (int i = 1; i <= numberOfTestcases; i++) { var testcase = new Testcase { Id = Guid.NewGuid().ToString(), Name = $"Testcase {i}" }; var numberOfBlockersForTestcase = rnd.Next(0, (int)Math.Ceiling(0.5 * numberOfBlockers)); while (testcase.BlockerIds.Count < numberOfBlockersForTestcase) { var blockerId = blockers[rnd.Next(0, numberOfBlockers)].Id; if (!testcase.BlockerIds.Contains(blockerId)) { testcase.BlockerIds.Add(blockerId); } } testcases.Add(testcase); } TestcaseBlockerDataset configuration = new TestcaseBlockerDataset { Blockers = blockers, Testcases = testcases }; return(configuration); }
void IBuildTaskService.SendTestcaseFile(string testsystemName, byte[] data) { object _lock = _testFileLocker.GetLock(testsystemName); lock (_lock) { Testsystem testsystem = _testsystemRepository.GetByName(testsystemName); testsystem.LastUpdated = DateTime.Now; _testsystemRepository.Store(testsystem); string testFile = RegtestingServerConfiguration.Testsfolder + testsystem.Filename; Directory.CreateDirectory(Path.GetDirectoryName(testFile)); using (FileStream fileStream = new FileStream(testFile, FileMode.Create, FileAccess.Write)) { fileStream.Write(data, 0, data.Length); } Logger.Log("UPDATE branch: " + testsystemName); TestcaseProvider testcaseProvider = new TestcaseProvider(testFile); testcaseProvider.CreateAppDomain(); foreach (string testcaseType in testcaseProvider.Types) { ITestable testable = testcaseProvider.GetTestableFromTypeName(testcaseType); if (testable == null) { continue; } Testcase testcase = _testcaseRepository.GetByType(testcaseType); string testableName = testable.GetName(); if (testcase == null) { Logger.Log("New test: " + testableName); testcase = new Testcase { Name = testableName, Type = testcaseType }; _testcaseRepository.Store(testcase); } else if (!testcase.Name.Equals(testableName)) { Logger.Log("Renamed test: " + testcase.Name + " to " + testableName); testcase.Name = testableName; _testcaseRepository.Store(testcase); } } testcaseProvider.Unload(); } }
void TestString (Testcase tc, string expected, NormalizationForm f) { string input = tc.Source; string actual = null; switch (f) { default: actual = Normalization.Normalize (input, 0); break; case NormalizationForm.FormD: actual = Normalization.Normalize (input, 1); break; case NormalizationForm.FormKC: actual = Normalization.Normalize (input, 2); break; case NormalizationForm.FormKD: actual = Normalization.Normalize (input, 3); break; } if (actual != expected) Console.WriteLine ("Error: expected {0} but was {1} (for {2},type{3} form {4})", expected, actual, tc.Source, tc.TestType, f); }
/// <summary> /// Get a single Result /// </summary> /// <param name="testsystem">the testsystem</param> /// <param name="testcase">the testcase</param> /// <param name="browser">the browser</param> /// <param name="language">the language</param> /// <returns>a result</returns> Result IResultRepository.Get(Testsystem testsystem, Testcase testcase, Browser browser, Language language) { Result result = ( from results in Session.Query <Result>() where results.Testsystem.ID == testsystem.ID && results.Testcase.ID == testcase.ID && results.Browser.ID == browser.ID && results.Language.ID == language.ID select results).FirstOrDefault(); return(result ?? new Result { Browser = browser, Language = language, Testsystem = testsystem, Testcase = testcase, ResultCode = TestState.NotSet }); }
private async Task AttachTestcase(ZipArchive zip, Problem prob, Testcase tc) { var prefix = $"data/{(tc.IsSecret ? "secret" : "sample")}/{tc.Rank}"; var inputFile = Store.GetFile(prob, $"t{tc.TestcaseId}.in"); using (var inputFile2 = inputFile.CreateReadStream()) await zip.CreateEntryFromStream(inputFile2, prefix + ".in"); var outputFile = Store.GetFile(prob, $"t{tc.TestcaseId}.out"); using (var outputFile2 = outputFile.CreateReadStream()) await zip.CreateEntryFromStream(outputFile2, prefix + ".ans"); if (tc.Description != $"{tc.Rank}") { zip.CreateEntryFromString(tc.Description, prefix + ".desc"); } if (tc.Point != 0) { zip.CreateEntryFromString($"{tc.Point}", prefix + ".point"); } }
private static string MapOutcome(Testcase test, TestResultSetDrop setDrop, TestRunStatisticsDrop testRunStatistics) { if (test.System_ErrSpecified || test.FailureSpecified) { setDrop.FailedCount++; testRunStatistics.FailedCount++; return("Failed"); } else if (test.Skipped != null) { setDrop.SkippedCount++; testRunStatistics.SkippedCount++; return("Skipped"); } else { setDrop.PassedCount++; testRunStatistics.PassedCount++; return("Passed"); } }
void RunTestcase(Testcase testcase) { // Arrange int[][] intervalsAsArrays = MakeArrays(testcase.Intervals); int[][] expectedAsArrays = MakeArrays(testcase.Expected); // Act int[][] result = Insert(intervalsAsArrays, testcase.NewInterval); // Assert Assert.AreEqual(expectedAsArrays.Length, result.Length, testcase.Name); for (var i = 0; i < result.Length; i++) { int[] interval = result[i]; int[] expected = expectedAsArrays[i]; Assert.AreEqual(expected[0], interval[0], testcase.Name); Assert.AreEqual(expected[1], interval[1], testcase.Name); } }
void ITestService.TestTestcaseOfTestsuite(int testerId, int testsystemId, int testsuiteId, int testcaseId) { Testsuite testsuite = _testsuiteRepository.GetById(testsuiteId); Testsystem testsystem = _testsystemRepository.GetById(testsystemId); Tester tester = _testerRepository.GetById(testerId); Testcase testcase = testsuite.Testcases.Single(t => t.ID == testcaseId); TestJob testJob = CreateTestJob("Testcase " + testcase.Name + "(Testsuite " + testsuite.Name + ")", testsuite, testsystem, tester); ITestJobManager testJobManager = new TestJobManager(testJob); ICollection <WorkItem> workItems = (from browser in testsuite.Browsers from language in testsuite.Languages select new WorkItem(testJobManager) { Testcase = testcase, Browser = browser, Language = language, Testsystem = testsystem, Tester = tester }).ToList(); _testPool.AddTestJob(testJobManager, workItems); }
private void SaveTests(IConfiguration configuration) { var db = DbHelpers.OpenDbConnection(configuration); foreach (var item in _testsFromXml.ListOfTests) { var inDb = db.Testcases.FirstOrDefault(i => i.TestcaseName == item.TestName); // Item already in db if (inDb != null) { continue; } // Item not in db var suite = db.Testsuites.FirstOrDefault(i => i.TestsuiteName == item.TestSuite); if (suite == null) { throw new Exception("TestSuite not found"); } var newTest = new Testcase { TestcaseName = item.TestName, BelongsToSuite = suite.TestsuiteId, TestcaseDescription = item.TestCaseDescription, TestSuite = suite }; db.Testcases.Add(newTest); db.SaveChanges(); } db.Dispose(); }
/// <summary> /// The post test result. /// </summary> /// <param name="testcase"> /// The testcase. /// </param> /// <param name="runId"> /// The run id. /// </param> public void PostTestResult(Testcase testcase, int runId) { this.TestrailClient.PostTestcaseResult(runId, testcase.Id, (int)testcase.Status, testcase.Summary); }
protected override Task <string> ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken, Testcase client) { var status = Status; var details = Details.Get(context).Replace("&", "&").Replace("<", "<").Replace(">", ">"); var attachment = Attachment.Get(context); if (status == TestcaseStatus.Pass) { return(client.TestcasePass(details, attachment)); } else { return(client.TestcaseFail(details, attachment)); } }
public static TestcaseBlockerDataset ImportFromExcel(string filename, ExcelImportOptions options) { if (string.IsNullOrEmpty(options.WorksheetName)) { throw new ArgumentException("WorksheetName is empty"); } if (string.IsNullOrEmpty(options.BlockerSeparator)) { throw new ArgumentException("BlockerSeparator is empty"); } if (options.ColumnNumberTestcaseId <= 0) { throw new ArgumentException("ColumnNumberTestcaseId must be greater than zero."); } if (options.ColumnNumberTestcaseName <= 0) { throw new ArgumentException("ColumnNumberTestcaseName must be greater than zero."); } if (options.ColumnNumberBlockerNames <= 0) { throw new ArgumentException("ColumnNumberBlockerNames must be greater than zero."); } if (options.FirstDataRow <= 0) { throw new ArgumentException("FirstDataRow must be greater than zero."); } try { var blockers = new List <Blocker>(); var testcases = new List <Testcase>(); FileInfo existingFile = new FileInfo(filename); using (var excel = new ExcelPackage(existingFile)) { var ws = excel.Workbook.Worksheets[options.WorksheetName]; if (!options.LastDataRow.HasValue) { options.LastDataRow = ws.Dimension.End.Row; } for (int row = options.FirstDataRow; row <= options.LastDataRow.Value; row++) { var testcaseId = (Convert.ToString(ws.Cells[row, options.ColumnNumberTestcaseId].Value)).Trim(); var testcaseName = (Convert.ToString(ws.Cells[row, options.ColumnNumberTestcaseName].Value)).Trim(); var blockerNamesString = (Convert.ToString(ws.Cells[row, options.ColumnNumberBlockerNames].Value)).Trim(); var blockerNames = new List <string>(blockerNamesString.Split(options.BlockerSeparator.ToCharArray())); var testtype = options.ColumnNumberTestType.HasValue ? (Convert.ToString(ws.Cells[row, options.ColumnNumberTestType.Value].Value)).Trim() : string.Empty; var applicationModule = options.ColumnNumberApplicationModule.HasValue ? (Convert.ToString(ws.Cells[row, options.ColumnNumberApplicationModule.Value].Value)).Trim(): string.Empty; var testcase = new Testcase { Id = testcaseId, Name = testcaseName, TestType = testtype, ApplicationModule = applicationModule }; foreach (var blockerName in blockerNames) { var trimmedBlockerName = blockerName.Trim().ToLower(); if (!string.IsNullOrEmpty(trimmedBlockerName)) { var existingBlocker = blockers.Where(x => x.Name == trimmedBlockerName).FirstOrDefault(); if (existingBlocker == null) { existingBlocker = new Blocker { Id = Guid.NewGuid().ToString().Replace("-", ""), Name = trimmedBlockerName, Cost = 1 }; blockers.Add(existingBlocker); } if (!testcase.BlockerIds.Contains(existingBlocker.Id)) { testcase.BlockerIds.Add(existingBlocker.Id); } } } testcases.Add(testcase); } } var dataset = new TestcaseBlockerDataset { Blockers = blockers, Testcases = testcases }; return(dataset); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
static unsafe void DataReceivedHandler(byte data) { // Debug.COM2.DisableDataReceivedInterrupt (); byte fn = Debug.COM2.Read(); if (fn != 0 && !connected) { return; } switch (fn) { case 0x00: // ask for connection if (!connected) { //TextMode.WriteLine ("Sending OK..."); Send((byte)1); connected = true; } else { //TextMode.WriteLine ("Sending NOK..."); Send((byte)0); } break; case 0x01: // test Send("Hello from SharpOS"); break; case 0x02: // dump memory //TextMode.WriteLine ("Memory dump request..."); // Memory dump needs one 32bits argument. int address = 0; address += Debug.COM2.Read(); address += (Debug.COM2.Read() << 8); address += (Debug.COM2.Read() << 16); address += (Debug.COM2.Read() << 24); // Byte dump is splitted into 16 packets of 256 bytes for (int counter = 0; counter < 16; counter++) { //TextMode.Write (address + 256 * counter, true); //TextMode.WriteLine (": dumping memory..."); if (!SafeSend((byte *)(address + 256 * counter), 256)) { break; } } break; case 0x03: int count = Testcase.GetTestCount(); if (!SafeSend(count)) { break; } Testcase.TestRecord *test = Testcase.GetFirstTest(); for (test = Testcase.GetFirstTest(); test != null; test = Testcase.GetNextTest(test)) { if (!SafeSend((byte *)(test->Source->Pointer), test->Source->Length)) { break; } if (!SafeSend((byte *)(test->Name->Pointer), test->Name->Length)) { break; } if (!SafeSend((byte)(test->Result ? 0x01 : 0x00))) { break; } } break; default: break; } // Debug.COM2.EnableDataReceivedInterrupt (); }
protected abstract Task <T> ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken, Testcase client);
private async Task LoadTestsetAsync(XElement name, ZipArchive zip) { if (name == null) { return; } Problem.TimeLimit = int.Parse(name.Element("time-limit").Value); Problem.MemoryLimit = int.Parse(name.Element("memory-limit").Value) >> 10; var count = int.Parse(name.Element("test-count").Value); var testName = name.Attribute("name").Value; var tests = name.Element("tests").Elements("test").ToList(); if (tests.Count != count) { throw new InvalidDataException("Zip corrupt."); } int rank = 0; for (int i = 1; i <= count; i++) { var fileName = $"{testName}/{i:D2}"; var test = tests[i - 1]; var attr1 = test.Attribute("description"); var attr2 = test.Attribute("sample"); var inp = zip.GetEntry(fileName); var outp = zip.GetEntry(fileName + ".a"); if (inp == null || outp == null) { Log($"Ignoring {fileName}.*"); continue; } var str = $"{i:D2}"; if (attr1 != null) { str += ": " + attr1.Value; } if (test.Attribute("method").Value == "generated") { str += "; " + test.Attribute("cmd").Value; } var tc = new Testcase { ProblemId = Problem.ProblemId, Description = str, IsSecret = attr2?.Value != "true", InputLength = (int)inp.Length, OutputLength = (int)outp.Length, Rank = ++rank, }; using (var ins = inp.Open()) tc.Md5sumInput = ins.ToMD5().ToHexDigest(true); using (var outs = outp.Open()) tc.Md5sumOutput = outs.ToMD5().ToHexDigest(true); await Store.CreateAsync(tc); using (var ins = inp.Open()) await Store.WriteFileAsync(Problem, $"t{tc.TestcaseId}.in", ins); using (var outs = outp.Open()) await Store.WriteFileAsync(Problem, $"t{tc.TestcaseId}.out", outs); Log($"Adding testcase t{tc.TestcaseId} '{fileName}.{{,a}}'."); } }
private async Task CreateTestcasesAsync(ZipArchive zip, string cat, bool secret) { var prefix = $"data/{cat}/"; var fileNames = zip.Entries .Where(z => z.FullName.StartsWith(prefix) && !z.FullName.EndsWith('/')) .Select(z => Path.GetFileNameWithoutExtension(z.FullName.Substring(prefix.Length))) .Distinct() .ToList(); fileNames.Sort((x, y) => { // check with prefix numbers int lenA = 0, lenB = 0; for (; lenA < x.Length; lenA++) { if (x[lenA] > '9' || x[lenA] < '0') { break; } } for (; lenB < y.Length; lenB++) { if (y[lenB] > '9' || y[lenB] < '0') { break; } } if (lenA == 0 || lenB == 0) { return(x.CompareTo(y)); } if (lenA != lenB) { return(lenA.CompareTo(lenB)); } return(x.CompareTo(y)); }); foreach (var file in fileNames) { var inp = zip.GetEntry(prefix + file + ".in"); var outp = zip.GetEntry(prefix + file + ".ans"); var desc = zip.GetEntry(prefix + file + ".desc"); var point = zip.GetEntry(prefix + file + ".point"); string usedParts = "in,out"; if (outp == null) { outp = zip.GetEntry(prefix + file + ".out"); } else { usedParts = "in,ans"; } if (inp == null || outp == null) { Log($"Ignoring {prefix}{file}.*"); continue; } var tc = new Testcase { ProblemId = Problem.ProblemId, Description = file, IsSecret = secret, InputLength = (int)inp.Length, OutputLength = (int)outp.Length, Rank = ++rank, }; if (desc != null) { using (var stream = desc.Open()) using (var reader = new StreamReader(stream)) { var content = await reader.ReadToEndAsync(); tc.Description = string.IsNullOrWhiteSpace(content) ? file : content.Trim(); } usedParts += ",desc"; } if (point != null) { using (var stream = point.Open()) using (var reader = new StreamReader(stream)) { var content = await reader.ReadToEndAsync(); if (int.TryParse(content.Trim(), out int pnt)) { tc.Point = pnt; } } usedParts += ",point"; } using (var ins = inp.Open()) tc.Md5sumInput = ins.ToMD5().ToHexDigest(true); using (var outs = outp.Open()) tc.Md5sumOutput = outs.ToMD5().ToHexDigest(true); await Store.CreateAsync(tc); using (var ins = inp.Open()) await Store.WriteFileAsync(Problem, $"t{tc.TestcaseId}.in", ins); using (var outs = outp.Open()) await Store.WriteFileAsync(Problem, $"t{tc.TestcaseId}.out", outs); Log($"Adding testcase t{tc.TestcaseId} 'data/{cat}/{file}.{{{usedParts}}}'."); } }
private async Task CreateTestcasesAsync(ZipArchive zip, string cat, bool secret) { var prefix = $"data/{cat}/"; var fileNames = zip.Entries .Where(z => z.FullName.StartsWith(prefix) && !z.FullName.EndsWith('/')) .Select(z => Path.GetFileNameWithoutExtension(z.FullName.Substring(prefix.Length))) .Distinct() .ToList(); fileNames.Sort(); foreach (var file in fileNames) { var inp = zip.GetEntry(prefix + file + ".in"); var outp = zip.GetEntry(prefix + file + ".ans"); var desc = zip.GetEntry(prefix + file + ".desc"); var point = zip.GetEntry(prefix + file + ".point"); if (inp == null || outp == null) { Log($"Ignoring {prefix}{file}.*"); continue; } var guid = Guid.NewGuid(); inp.ExtractToFile($"{guid}.in", true); outp.ExtractToFile($"{guid}.ans", true); var tc = new Testcase { ProblemId = Problem.ProblemId, Description = file, IsSecret = secret, InputLength = (int)inp.Length, OutputLength = (int)outp.Length, Rank = ++rank, }; if (desc != null) { using (var stream = desc.Open()) using (var reader = new StreamReader(stream)) { var content = await reader.ReadToEndAsync(); tc.Description = string.IsNullOrWhiteSpace(content) ? file : content.Trim(); } } if (point != null) { using (var stream = point.Open()) using (var reader = new StreamReader(stream)) { var content = await reader.ReadToEndAsync(); if (int.TryParse(content.Trim(), out int pnt)) { tc.Point = pnt; } } } var inp2 = await File.ReadAllBytesAsync($"{guid}.in"); tc.Md5sumInput = inp2.ToMD5().ToHexDigest(true); inp2 = await File.ReadAllBytesAsync($"{guid}.ans"); tc.Md5sumOutput = inp2.ToMD5().ToHexDigest(true); var t = dbContext.Testcases.Add(tc); await dbContext.SaveChangesAsync(); File.Move($"{guid}.in", $"Problems/p{Problem.ProblemId}/t{t.Entity.TestcaseId}.in"); File.Move($"{guid}.ans", $"Problems/p{Problem.ProblemId}/t{t.Entity.TestcaseId}.out"); Log($"Adding testcase t{t.Entity.TestcaseId} 'data/{cat}/{file}.{{in,ans}}."); } }