Previously, we implemented the functions of LexicalAnalysis, DynamicDataSet, and ExpressionAnalysis. Today we will talk about how to use them to add a script for the project.
Sometimes we need to dynamically execute some simple condition judgments in the project. For example, when writing an automatic test framework, we must support users to manually write some Check scripts. For example
We have completed a test case. After the test is completed, we have obtained a lot of table data related to this test case from the database. Some of the data is created in this test case, some data
Modified in this test, and some data is deleted. Therefore, to verify the results of this test case, we must write many small assertions, if scripts are supported, it is easy to write these assertions.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Contracts;
using Zxf.ExpressionBuilder;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
dynamic dynamicDataSet = new DynamicDataSet(PrepareDataSet());
var dynamicLambdaExpFunc1 = BuildFunc("Data.Test.Message[0].ToString().StartsWith(\"Hello\")",dynamicDataSet);
var result1 = dynamicLambdaExpFunc1.Invoke(dynamicDataSet);
Contract.Assert((bool)result1 == true);
var dynamicLambdaExpFunc2 = BuildFunc("Data.Test.Message[0].ToString().ToUpper()", dynamicDataSet);
var result2 = dynamicLambdaExpFunc2.Invoke(dynamicDataSet);
Contract.Assert((string)result2 == "Hello, World!".ToUpper());
var dynamicLambdaExpFunc3 = BuildFunc("Data.Test.Count == 1", dynamicDataSet);
var result3 = dynamicLambdaExpFunc3.Invoke(dynamicDataSet);
Contract.Assert((bool)result3 == true);
}
private static Func<DynamicDataSet, object> BuildFunc(string code, DynamicDataSet parameter)
{
List<LexicalBlock> lexicalBlocks = new LexicalAnalysis().Analysis(new string[] { code });
Dictionary<string,Type> parameterTypes = new Dictionary<string,Type>();
parameterTypes.Add("Data",typeof(DynamicDataSet));
return ExpressionAnalysis.Analysis<Func<DynamicDataSet, object>>(lexicalBlocks, parameterTypes);
}
private static DataSet PrepareDataSet()
{
DataTable dataTable = new DataTable("Test");
dataTable.Columns.Add("Message", typeof(string));
DataRow dataRow = dataTable.NewRow();
dataRow[0] = "Hello, World!";
dataTable.Rows.Add(dataRow);
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dataTable);
return dataSet;
}
}
}