public void RandomSymbolFromStringTest_LongString_20times_NotCompare() { // arrange var line = "asadfghjkhkjghgdfretyui"; var fakeRandomIntegerProvider = new Mock <IGenerateInteger>(); fakeRandomIntegerProvider.Setup(f => f.Generate(0, line.Length - 1)).Returns(0); var realRamdomIntegerProvider = new RandomIntegerProvider(); string valuesFromFake = string.Empty; string valuesFromReal = string.Empty; // act for (int i = 0; i < 20; i++) { valuesFromFake += LineParser.RandomSymbolFromString(line, fakeRandomIntegerProvider.Object); valuesFromReal += LineParser.RandomSymbolFromString(line, realRamdomIntegerProvider); } // assert fakeRandomIntegerProvider.Verify(f => f.Generate(0, line.Length - 1), Times.Exactly(20)); Assert.NotEqual(valuesFromReal, valuesFromFake); }
public DefaultHttpResponseParserFactory(LineParser lineParser, HttpResponseFactory responseFactory) : base() { this.lineParser = lineParser != null ? lineParser : BasicLineParser.Instance; this.responseFactory = responseFactory != null ? responseFactory : DefaultHttpResponseFactory .Instance; }
public void LineParser_InvalidRHS_ReturnsInvalidSyntax() { string line = "\tproposition ( p and q ) ifandonlyif z r"; SyntacticElement parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
/// <inheritdoc /> public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } /* * Syntax * BYPASSCF "URL" ["UA"] * */ Url = LineParser.ParseLiteral(ref input, "URL"); if (input != "") { UserAgent = LineParser.ParseLiteral(ref input, "UA"); } return(this); }
public void DoJob(string symbols, int n) { int _n = 0; Parallel.ForEach(symbols, sym => { int N = 0; //System.Threading.Thread.Sleep(new Random().Next(1, 5) * 1000); string text = string.Empty; lock (lockerProv) text = _provider.ReadAll(); var count = LineParser.SymRepeats(text, sym); lock (lockerN) { _n++; N = _n; } if (N % n == 0) { var rsym = LineParser.RandomSymbolFromString(symbols, new RandomIntegerProvider()); lock (lockerProv) _provider.Write(rsym, true); } OnUpdate?.Invoke(this, new CustomEventArgs(count, sym, _provider.LastModified)); }); }
/// <inheritdoc /> public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } /* * Syntax: * ELEMENTACTION ID "id" 0 RECURSIVE? ACTION ["INPUT"] [-> VAR/CAP "OUTPUT"] * */ Locator = (ElementLocator)LineParser.ParseEnum(ref input, "LOCATOR", typeof(ElementLocator)); ElementString = LineParser.ParseLiteral(ref input, "STRING"); if (LineParser.Lookahead(ref input) == TokenType.Boolean) { LineParser.SetBool(ref input, this); } else if (LineParser.Lookahead(ref input) == TokenType.Integer) { ElementIndex = LineParser.ParseInt(ref input, "INDEX"); } Action = (ElementAction)LineParser.ParseEnum(ref input, "ACTION", typeof(ElementAction)); if (input == "") { return(this); } if (LineParser.Lookahead(ref input) == TokenType.Literal) { Input = LineParser.ParseLiteral(ref input, "INPUT"); } // Try to parse the arrow, otherwise just return the block as is with default var name and var / cap choice if (LineParser.ParseToken(ref input, TokenType.Arrow, false) == "") { return(this); } // Parse the VAR / CAP try { var varType = LineParser.ParseToken(ref input, TokenType.Parameter, true); if (varType.ToUpper() == "VAR" || varType.ToUpper() == "CAP") { IsCapture = varType.ToUpper() == "CAP"; } } catch { throw new ArgumentException("Invalid or missing variable type"); } // Parse the variable/capture name try { OutputVariable = LineParser.ParseToken(ref input, TokenType.Literal, true); } catch { throw new ArgumentException("Variable name not specified"); } return(this); }
public void LineParserAndCulture() { var currentCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE"); Random rand = new Random(); var arraySize = 100; var data = new float[arraySize]; var separator = new string[2] { " ", "\t" }; for (int sep = 0; sep < 4; sep++) { for (int i = 0; i < arraySize; i++) { data[i] = rand.NextSingle() * 50 - 25; } var result = LineParser.ParseKeyThenNumbers("word" + separator[sep % 2] + string.Join(separator[sep / 2], data.Select(x => x.ToString("G9"))), false); Assert.True(result.isSuccess); Assert.Equal("word", result.key); for (int i = 0; i < arraySize; i++) { Assert.Equal(data[i], result.values[i]); } } Thread.CurrentThread.CurrentCulture = currentCulture; }
/// <inheritdoc /> public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } /* * Syntax: * NAVIGATE "URL" [TIMEOUT] [BanOnTimeout?] * */ Url = LineParser.ParseLiteral(ref input, "URL"); if (LineParser.Lookahead(ref input) == TokenType.Integer) { Timeout = LineParser.ParseInt(ref input, "TIMEOUT"); } if (LineParser.Lookahead(ref input) == TokenType.Boolean) { LineParser.SetBool(ref input, this); } return(this); }
static long First(string inputFile) { var lines = new LineParser().ReadData(inputFile); var errorScore = 0L; foreach (var line in lines) { var stack = new Stack <char>(); foreach (var c in line) { if (ChunkPairs.IsOpenCharacter(c)) { stack.Push(c); } if (ChunkPairs.IsCloseCharacter(c)) { var pair = ChunkPairs.FindByCloseCharacter(c); if (stack.Peek() != pair.OpenCharacter) { //syntax error errorScore += pair.SyntaxErrorScore; break; } stack.Pop(); } } } return(errorScore); }
public void LineParser__NoPropositionSymbol_ReturnsInvalidSyntax() { string line = "\tproposition p q "; SyntacticElement parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
public void LineParser_TooManyIfAndOnlyIfs_ReturnsInvalidSyntax() { string line = "\tproposition p implies q implies z"; SyntacticElement parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
private void ProcessToken(MUDToken token) { if (token.TokenType == MUDTokenType.Text) { Run run = new Run(token.Content.ToString()); run.Foreground = new SolidColorBrush(CurrentColor.ForegroundColor); run.Background = new SolidColorBrush(CurrentColor.BackgroundColor); this.Interface.OutputConsole.AddRun(run); // parse the line now that new text has been added to it. LineParser.ParseLine(this.Interface.OutputConsole.LastParagraph(), this); } else if (token.TokenType == MUDTokenType.Color) { CurrentColor.Update(token); } else if (token.TokenType == MUDTokenType.NewLine) { this.Interface.OutputConsole.AddNewParagraph(); } else if (token.TokenType == MUDTokenType.EraseLine) { this.Interface.OutputConsole.ClearLastParagraph(); } else if (token.TokenType == MUDTokenType.CursorBackward) { // do nothing for now. Maybe forever. } CurrentParseState = CurrentParseState.Execute(token, this); }
/// <inheritdoc /> public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } /* * Syntax: * BROWSERACTION ACTION ["INPUT"] * */ Action = (BrowserAction)LineParser.ParseEnum(ref input, "ACTION", typeof(BrowserAction)); if (input != string.Empty && !input.StartsWith("USERAGENT \"")) { Input = LineParser.ParseLiteral(ref input, "INPUT"); } if (Action == BrowserAction.Open && input != string.Empty) { SUserAgent = LineParser.ParseLiteral(ref input, "USERAGENT"); } return(this); }
public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } Lang = LineParser.ParseToken(ref input, TokenType.Parameter, false); Base64Captcha = LineParser.ParseLiteral(ref input, nameof(Base64Captcha)); if (LineParser.ParseToken(ref input, TokenType.Arrow, false) == "") { return(this); } // Parse the variable/capture name try { InputVariableName = LineParser.ParseToken(ref input, TokenType.Literal, true); } catch { throw new ArgumentException("Variable name not specified"); } return(this); }
/// <inheritdoc /> public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } /* * Syntax: * CAPTCHA "URL" [BASE64? USESCREEN?] -> VAR "CAP" * */ Url = LineParser.ParseLiteral(ref input, "URL"); while (LineParser.Lookahead(ref input) == TokenType.Boolean) { LineParser.SetBool(ref input, this); } LineParser.EnsureIdentifier(ref input, "->"); LineParser.EnsureIdentifier(ref input, "VAR"); // Parse the variable name VariableName = LineParser.ParseLiteral(ref input, "VARIABLE NAME"); return(this); }
// example "$GPRMC,054016.000,A,3238.8270,N,09723.6242,W,0.21,124.65,160714,,,D*77\r" // "$GPRMC,033841.000,A,3238.8235 ,N,09723.6235,W,0.18,283.00,170714,,,D*7B\r" // "$GPRMCA,3238.8195,N,09723.6229,W,0.27,307.31,170714,,,D*7F\r" public static GeoLocation GetGeoLocation(String geoLocationString) { GeoLocation location = new GeoLocation(); location.setValid(false); try { LineParser parser = new LineParser(geoLocationString); if (geoLocationString.StartsWith("$GPRMC,") || geoLocationString.StartsWith("$GPGGA")) // make sure it's a valid gps string { double tryParseOutput; String nmeaLatitude = parser.GetValueAtPosition(latitudePosition); String nmeaDegrees = nmeaLatitude.Substring(0, 2); String nmeaMinutes = nmeaLatitude.Substring(2, nmeaLatitude.IndexOf(".") - 2); String nmeaSeconds = nmeaLatitude.Substring(nmeaLatitude.IndexOf(".") + 1); if (double.TryParse(nmeaDegrees, out tryParseOutput) && double.TryParse(nmeaMinutes, out tryParseOutput) && double.TryParse(nmeaSeconds, out tryParseOutput)) // checksum { double googleLatitude = Math.Round(double.Parse(nmeaDegrees) + (double.Parse(nmeaMinutes) / 60) + ((double.Parse(nmeaSeconds) / 100) / 3600), 4); if (parser.GetValueAtPosition(northSouthPosition) == "S" && googleLatitude > 0) { googleLatitude = -googleLatitude; } String nmeaLongitude = parser.GetValueAtPosition(longitudePosition); nmeaDegrees = nmeaLongitude.Substring(0, 3); nmeaMinutes = nmeaLongitude.Substring(3, nmeaLatitude.IndexOf(".") - 2); nmeaSeconds = nmeaLongitude.Substring(nmeaLatitude.IndexOf(".") + 2); if (double.TryParse(nmeaDegrees, out tryParseOutput) && double.TryParse(nmeaMinutes, out tryParseOutput) && double.TryParse(nmeaSeconds, out tryParseOutput)) // checksum { double googleLongitude = Math.Round(double.Parse(nmeaDegrees) + (double.Parse(nmeaMinutes) / 60) + ((double.Parse(nmeaSeconds) / 100) / 3600), 4); if (parser.GetValueAtPosition(eastWestPosition) == "W" && googleLongitude > 0) { googleLongitude = -googleLongitude; } location.SetLatitude(googleLatitude); location.SetLongitude(googleLongitude); location.SetKnots(StringFunctions.ParseDouble(parser.GetValueAtPosition(knotsPosition))); location.SetNorthSouth(parser.GetValueAtPosition(northSouthPosition)); location.SetEastWest(parser.GetValueAtPosition(eastWestPosition)); location.SetValidity(parser.GetValueAtPosition(validityPosition)); location.setValid(true); } } } } catch (Exception ex) { // If we are in here, something in the string was malformed. No need to alert the user, we'll get another // update in a few seconds. ex.ToString(); // just to get rid of the warning } return(location); }
/// <inheritdoc /> public override BlockBase FromLS(string line) { // Trim the line var input = line.Trim(); // Parse the label if (input.StartsWith("#")) { Label = LineParser.ParseLabel(ref input); } // Parse the function TCPCommand = (TCPCommand)LineParser.ParseEnum(ref input, "Command", typeof(TCPCommand)); // Parse specific function parameters switch (TCPCommand) { case TCPCommand.Connect: Host = LineParser.ParseLiteral(ref input, "Host"); Port = LineParser.ParseLiteral(ref input, "Port"); if (LineParser.Lookahead(ref input) == TokenType.Boolean) { LineParser.SetBool(ref input, this); } break; case TCPCommand.Send: Message = LineParser.ParseLiteral(ref input, "Message"); break; default: break; } // Try to parse the arrow, otherwise just return the block as is with default var name and var / cap choice if (LineParser.ParseToken(ref input, TokenType.Arrow, false) == "") { return(this); } // Parse the VAR / CAP try { var varType = LineParser.ParseToken(ref input, TokenType.Parameter, true); if (varType.ToUpper() == "VAR" || varType.ToUpper() == "CAP") { IsCapture = varType.ToUpper() == "CAP"; } } catch { throw new ArgumentException("Invalid or missing variable type"); } // Parse the variable/capture name try { VariableName = LineParser.ParseToken(ref input, TokenType.Literal, true); } catch { throw new ArgumentException("Variable name not specified"); } return(this); }
public WriterPerformanceLog(FileStream fileStream) { this.fileStream = fileStream; this.writer = new StreamWriter(fileStream); buffer = new Byte[512]; lineParser = new LineParser(writer.Encoding, 512, 512); }
/// <summary>Creates new instance of DefaultHttpRequestParser.</summary> /// <remarks>Creates new instance of DefaultHttpRequestParser.</remarks> /// <param name="buffer">the session input buffer.</param> /// <param name="lineParser"> /// the line parser. If <code>null</code> /// <see cref="Org.Apache.Http.Message.BasicLineParser.Instance">Org.Apache.Http.Message.BasicLineParser.Instance /// </see> /// will be used. /// </param> /// <param name="requestFactory"> /// the response factory. If <code>null</code> /// <see cref="Org.Apache.Http.Impl.DefaultHttpRequestFactory.Instance">Org.Apache.Http.Impl.DefaultHttpRequestFactory.Instance /// </see> /// will be used. /// </param> /// <param name="constraints"> /// the message constraints. If <code>null</code> /// <see cref="Org.Apache.Http.Config.MessageConstraints.Default">Org.Apache.Http.Config.MessageConstraints.Default /// </see> /// will be used. /// </param> /// <since>4.3</since> public DefaultHttpRequestParser(SessionInputBuffer buffer, LineParser lineParser, HttpRequestFactory requestFactory, MessageConstraints constraints) : base(buffer , lineParser, constraints) { this.requestFactory = requestFactory != null ? requestFactory : DefaultHttpRequestFactory .Instance; this.lineBuf = new CharArrayBuffer(128); }
public void ShouldReturnCorrectWarehouseName() { PrepareData(); var result = new LineParser().Parse(correctLine); Assert.Equal("WH-A", result.First().Name); }
public void ShouldReturnCorrectMaterialId() { PrepareData(); var result = new LineParser().Parse(correctLine); Assert.Equal("COM-124047", result.First().MaterialLists.First().Id); }
public void ShouldReturnCorrectMaterialQuantity() { PrepareData(); var result = new LineParser().Parse(correctLine); Assert.Equal(15, result.First().MaterialLists.First().Quantity); }
public void ExpressionParser_SimpleNot_WithRHS_ReturnsInvalidSyntacticExpression() { string line = "bob not dave"; SyntacticElement parseResult; parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
public void ExpressionParser_DoublePredicate_ReturnsInvalidSyntacticElement() { string line = "bob dave"; SyntacticElement parseResult; parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
public FileFollower(AutoResetEvent dataAvailableEvent, String filename, Int32 readBufferSize) : base(dataAvailableEvent) { this.fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); this.lineParser = new LineParser(Encoding.ASCII, ByteBuffer.DefaultInitialCapacity, ByteBuffer.DefaultExpandLength); this.readBuffer = new Byte[readBufferSize]; }
public void ExpressionParser_SimpleNotInMultiBrackets_ReturnsExpression() { string line = "((not)(dave))"; SyntacticElement parseResult; parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
public void ExpressionParser_AandBnoStartBrace_ReturnsExpression() { string line = "A and B)"; SyntacticElement parseResult; parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
public void ExpressionParser_PredicateNotExpression_ReturnsInvalidSyntax() { string line = "P (not(Q))"; SyntacticElement parseResult; parseResult = LineParser.Parse(line); Assert.AreEqual(typeof(InvalidSyntacticElement), parseResult.GetType()); }
public void ParseDictionary_MultiEntry_Parse() { var input = "{ (\"key1\", \"value1\"), (\"key2\", \"value2\") }"; var dict = LineParser.ParseDictionary(ref input); Assert.Equal("value1", dict["key1"]); Assert.Equal("value2", dict["key2"]); }
public void WhenProvidedAValidInputParserParsesKeyAndValues(string input, string expectedKey, float[] expectedValues) { var result = LineParser.ParseKeyThenNumbers(input); Assert.True(result.isSuccess); Assert.Equal(expectedKey, result.key); Assert.Equal(expectedValues, result.values); }
private static void Main(string[] args) { var reader = new LineReader(); var parser = new LineParser(); using (var writer = new LineWriter(args[1])) { foreach (var line in parser.ParseLines(reader.GetLines(args[0]))) writer.WriteLine(line.Item1, line.Item2); } Console.WriteLine("Press a key to finish"); Console.ReadKey(true); }
public void LineParseNullsTest() { // Arrange var line = @"Jane Doe,[email protected],F,,128,,1234,,98765,,1234567890,,1.2,,3.4,,3.1416,,27/10/2007,"; // Act var lineParser = new LineParser<Foo>(); var parseResult = lineParser.Parse(line); // Assert Assert.IsNotNull(parseResult); Assert.IsNull(parseResult.Errors); var actual = parseResult.Instance; var expected = new Foo() { StringProperty = "Jane Doe", StringPropertyWithPattern = "*****@*****.**", CharProperty = 'F', NullableCharProperty = null, ByteProperty = 128, NullableByteProperty = null, Int16Property = 1234, NullableInt16Property = null, Int32Property = 98765, NullableInt32Property = null, Int64Property = 1234567890, NullableInt64Property = null, SingleProperty = 1.2F, NullableSingleProperty = null, DoubleProperty = 3.4, NullableDoubleProperty = null, DecimalProperty = 3.1416m, NullableDecimalProperty = null, DateTimeProperty = new DateTime(2007, 10, 27), NullableDateTimeProperty = null, }; Assert.AreEqual<Foo>(expected, actual); }
private static void Main(string[] args) { if (args.Length < 1) { System.Console.WriteLine("Usage: PageFaults.Console <file name>"); System.Console.WriteLine(" where <file name> contains a number of lines of the form:"); System.Console.WriteLine(" F,3,0,1,2,3,..."); System.Console.WriteLine(" The first item should be the page replacement algorithm"); System.Console.WriteLine(" with F = FIFO, L = LRU, O = Optimal."); System.Console.WriteLine(" The second item should be the cache size (3 in this case)."); System.Console.WriteLine(" The rest of the items represent the pages being accessed."); System.Console.WriteLine(" The program will display the pages in the cache for each step and end with the total number of page faults."); return; } var parser = new LineParser(); var lines = File.ReadAllLines(args[0]); foreach (var line in lines) { System.Console.WriteLine(line); RunOnce(parser.Parse(line)); } }
public void EmptyLineParsePositionalTest() { // Arrange var line = ""; // Act var lineParser = new LineParser<SimpleOrder>(new PositionalValuesFieldsSplitter<SimpleOrder>()); var parseResult = lineParser.Parse(line); // Assert Assert.IsNull(parseResult.Errors); var actual = parseResult.Instance; Assert.IsNotNull(actual); var expected = new SimpleOrder() { OrderId = 0, Freight = 0m, ShipAddress = null, DeliveryDate = DateTime.MinValue, }; Assert.AreEqual<SimpleOrder>(expected, actual); }
public void LineParseWithErrorsTest() { // Arrange var line = @"Jane Doe,[email protected],F,,128,,ABCD,,98765,,1234567890,,*,,3.4,,3.1416,,99/99/9999,"; // Act var lineParser = new LineParser<Foo>(); var parseResult = lineParser.Parse(line); // Assert Assert.IsNotNull(parseResult.Errors); var expectedErrorCount = 3; var actualErrorCount = parseResult.Errors.Count(); Assert.AreEqual<int>(expectedErrorCount, actualErrorCount); var expectedErrorMessages = new string[] { "Int16Property: Unparsable System.Int16 >>> ABCD", "SingleProperty: Unparsable System.Single >>> *", "DateTimeProperty: Unparsable System.DateTime >>> 99/99/9999" }; var actualErrorMessages = parseResult.Errors; Assert.IsTrue(expectedErrorMessages.SequenceEqual(actualErrorMessages)); }
public void ShortLineParsePositionalTest() { // Arrange string address = "*****@*****.**"; var line = $" 1234 3.1416{address,-30}";//input line length is less than declared total length. // Act var lineParser = new LineParser<SimpleOrder>(new PositionalValuesFieldsSplitter<SimpleOrder>()); var parseResult = lineParser.Parse(line); // Assert Assert.IsNull(parseResult.Errors); var actual = parseResult.Instance; Assert.IsNotNull(actual); var expected = new SimpleOrder() { OrderId = 1234, Freight = 3.1416m, ShipAddress = address, DeliveryDate = DateTime.MinValue, }; Assert.AreEqual<SimpleOrder>(expected, actual); }
public void NullLineParsePositionalTest() { // Arrange string line = null; // Act var lineParser = new LineParser<SimpleOrder>(new PositionalValuesFieldsSplitter<SimpleOrder>()); var parseResult = lineParser.Parse(line); // Assert Assert.Fail("Null input line must throw an exception."); }
public void ZeroLengthFieldParsePositionalTest() { // Arrange var line = $" 1234ABCDE";//input line length is invalid field length. // Act var lineParser = new LineParser<BadRecord2>(new PositionalValuesFieldsSplitter<BadRecord2>()); var parseResult = lineParser.Parse(line); // Assert Assert.Fail("Positional field with non-positive length must throw an exception."); }
public void LineParsePositionalTest() { // Arrange string address = "*****@*****.**"; var line = $" 1234 3.1416{address,-50}25/12/2007"; // Act var lineParser = new LineParser<SimpleOrder>(new PositionalValuesFieldsSplitter<SimpleOrder>()); var parseResult = lineParser.Parse(line); // Assert Assert.IsNull(parseResult.Errors); var actual = parseResult.Instance; Assert.IsNotNull(actual); var expected = new SimpleOrder() { OrderId = 1234, Freight = 3.1416m, ShipAddress = address, DeliveryDate = new DateTime(2007, 12, 25), }; Assert.AreEqual<SimpleOrder>(expected, actual); }
void IgnorePostedParser(string line) { if (postedRegex.IsMatch(line)) { if (postedCount == 1) { currentParser = BuildStateParser; } else { postedCount--; }//else }//if }
public void LineParseUsingTabsAsDelimiterTest() { // Arrange var line = "Jane Doe\[email protected]\tF\t\t128\t\t1234\t\t98765\t\t1234567890\t\t1.2\t\t3.4\t\t3.1416\t\t25/12/2007\t"; // Act var fieldsSplitter = new DelimiterSeparatedValuesFieldsSplitter<Foo>(delimiter: '\t'); var lineParser = new LineParser<Foo>(fieldsSplitter); var parseResult = lineParser.Parse(line); // Assert Assert.IsNull(parseResult.Errors); var actual = parseResult.Instance; var expected = new Foo() { StringProperty = "Jane Doe", StringPropertyWithPattern = "*****@*****.**", CharProperty = 'F', NullableCharProperty = null, ByteProperty = 128, NullableByteProperty = null, Int16Property = 1234, NullableInt16Property = null, Int32Property = 98765, NullableInt32Property = null, Int64Property = 1234567890, NullableInt64Property = null, SingleProperty = 1.2F, NullableSingleProperty = null, DoubleProperty = 3.4, NullableDoubleProperty = null, DecimalProperty = 3.1416m, NullableDecimalProperty = null, DateTimeProperty = new DateTime(2007, 12, 25), NullableDateTimeProperty = null, }; Assert.AreEqual<Foo>(expected, actual); }
public void SetUp() { sut = new LineParser(); }
void GettingPlayersParser(string line) { var match = playerRegex.Match(line); if (match.Success) { var name = match.Value.Replace(" : [", ""); Player player; if (name == playingAs) { player = new Player(name, true); player.Cards = ExtractCards(line); } else { player = new Player(name, false); } players.Add(player); } else if (dealerPositionRegex.IsMatch(line)) { currentParser = IgnorePostedParser; }//else if }
public void LineParserCreateTest() { // Arrange var properties = typeof(Foo).GetProperties(); var expected = properties.Count(); // Act var lineParser = new LineParser<Foo>(); var actual = lineParser.FieldParsers.Count(); // Assert // There has to be as many FieldParsers as Properties in the target type... Assert.AreEqual<int>(expected, actual); // ...and there has to be one single field for every property in ClassForTesting... foreach(var field in lineParser.FieldParsers) { Assert.IsNotNull(properties.Single(p => p.Name.Equals(field.FieldName))); } }
void Parse(List<string> lines) { currentParser = GettingPlayersParser; foreach (var line in lines) { currentParser(line); }//foreach }
public LineParserTest() { _parser = new LineParser(); }