Skip to content

Instantly share code, notes, and snippets.

@mkoertgen
Created February 12, 2015 09:37
Show Gist options
  • Save mkoertgen/9e4bacfb891d62102a02 to your computer and use it in GitHub Desktop.
Save mkoertgen/9e4bacfb891d62102a02 to your computer and use it in GitHub Desktop.
A learning test for Expression Evaluator
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);
}
}
}
}
@mkoertgen
Copy link
Author

AntLr uses BSD license, so you need to reproduce the copyright when using the package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment