Created
February 12, 2015 09:37
-
-
Save mkoertgen/9e4bacfb891d62102a02 to your computer and use it in GitHub Desktop.
A learning test for Expression Evaluator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
using ExpressionEvaluator; | |
using FluentAssertions; | |
using NUnit.Framework; | |
namespace Hello.Expressions | |
{ | |
[TestFixture] | |
class ExpressionTests | |
{ | |
[Test] | |
public void DateTimeTest() | |
{ | |
const string dateFormat = "yyyy-MM-dd HH:mm:ss.fff"; | |
var culture = CultureInfo.InvariantCulture; | |
var reg = new TypeRegistry(); | |
reg.RegisterType<DateTime>("DateTime"); | |
reg.RegisterType<TimeSpan>("TimeSpan"); | |
reg.RegisterSymbol("InvariantCulture", culture); | |
var expression = new CompiledExpression<DateTime>("DateTime.Now - TimeSpan.FromDays(1)") { TypeRegistry = reg }; | |
var actual = expression.Eval(); | |
var expected = DateTime.Now - TimeSpan.FromDays(1); | |
actual.Should().BeCloseTo(expected); | |
var input = String.Format("DateTime.ParseExact('{0}', '{1}', InvariantCulture)", expected.ToString(dateFormat), dateFormat); | |
expression = new CompiledExpression<DateTime>(input) { TypeRegistry = reg}; | |
actual = expression.Eval(); | |
actual.Should().BeCloseTo(expected); | |
reg.RegisterSymbol("d", new SimplerDate(dateFormat, culture)); | |
input = String.Format("d.Parse('{0}')", expected.ToString(dateFormat)); | |
expression = new CompiledExpression<DateTime>(input) { TypeRegistry = reg }; | |
actual = expression.Eval(); | |
actual.Should().BeCloseTo(expected); | |
} | |
class SimplerDate | |
{ | |
public const string DefaultFormat = "yyyy-MM-dd HH:mm:ss.fff"; | |
private readonly string _format; | |
private readonly IFormatProvider _culture; | |
public SimplerDate(string format = null, IFormatProvider culture = null) | |
{ | |
_format = format ?? DefaultFormat; | |
_culture = culture ?? CultureInfo.InvariantCulture; | |
} | |
public DateTime Parse(string value) | |
{ | |
return DateTime.ParseExact(value, _format, _culture); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AntLr uses BSD license, so you need to reproduce the copyright when using the package.