Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
2010-02-13 Gonzalo Paniagua Javier <gonzalo@novell.com>
* System.Collections.Generic/HashSetTest.cs: fix and test for bug
#579791. Patch from Tiaan Geldenhuys.
2009-08-30 Zoltan Varga <vargaz@gmail.com>
* HashSetTest.cs: Fix warnings.
2009-07-30 Raja R Harinath <harinath@hurrynot.org>
* HashSetTest.cs (Enumerate_Current): New test, including cases
from #491858, #517415.
2009-07-09 Jb Evain <jbevain@novell.com>
* HashSetTest.cs: add test for #520760, ICollection<T>.Add
should not throw on duplicates.
2008-12-17 Jb Evain <jbevain@novell.com>
* HashSetTest.cs: add test for CopyTo.
2008-05-15 Roei Erez <roeie@mainsoft.com>
* HashSetTest.cs: temporary exclude CopyTo in JAVAEE environment
2007-11-28 Jb Evain <jbevain@novell.com>
* HashSetTest.cs: tests for HashSet<T>.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
2010-05-25 Jb Evain <jbevain@novell.com>
* MemoryMappedFileTest.cs: use proper overloads.
2009-09-05 Zoltan Varga <vargaz@gmail.com>
* MemoryMappedFileTest.cs: Add a minimal test for CreateViewAccessor ().
2009-08-30 Zoltan Varga <vargaz@gmail.com>
* MemoryMappedFileTest.cs: New file.

View File

@@ -0,0 +1,323 @@
//
// MemoryMappedFileTest.cs
//
// Author:
// Zoltan Varga (vargaz@gmail.com)
//
// (C) 2009 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_4_0
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using NUnit.Framework;
namespace MonoTests.System.IO.MemoryMappedFiles {
[TestFixture]
public class MemoryMappedFileTest {
void AssertThrows<ExType> (Action del) where ExType : Exception {
bool thrown = false;
try {
del ();
} catch (ExType) {
thrown = true;
}
Assert.IsTrue (thrown);
}
static int named_index;
static String MkNamedMapping ()
{
return "test-" + named_index++;
}
static string tempDir = Path.Combine (Path.GetTempPath (), typeof (MemoryMappedFileTest).FullName);
string fname;
[SetUp]
protected void SetUp () {
if (Directory.Exists (tempDir))
Directory.Delete (tempDir, true);
Directory.CreateDirectory (tempDir);
fname = Path.Combine (tempDir, "basic.txt");
using (StreamWriter sw = new StreamWriter (fname)) {
sw.WriteLine ("Hello!");
sw.WriteLine ("World!");
}
}
[TearDown]
protected void TearDown () {
if (Directory.Exists (tempDir))
Directory.Delete (tempDir, true);
}
[Test]
public void Basic () {
var file = MemoryMappedFile.CreateFromFile (fname, FileMode.Open);
using (var stream = file.CreateViewStream ()) {
TextReader r = new StreamReader (stream);
string s;
s = r.ReadLine ();
Assert.AreEqual ("Hello!", s);
s = r.ReadLine ();
Assert.AreEqual ("World!", s);
}
}
[Test]
public void CreateNew ()
{
// This must succeed
MemoryMappedFile.CreateNew (Path.Combine (tempDir, "createNew.test"), 8192);
}
[Test]
[ExpectedException (typeof (IOException))]
public void CreateNew_OnExistingFile ()
{
// This must succeed
MemoryMappedFile.CreateNew (Path.Combine (tempDir, "createNew.test"), 8192);
// This should fail, the file exists
MemoryMappedFile.CreateNew (Path.Combine (tempDir, "createNew.test"), 8192);
}
// Call this twice, it should always work
[Test]
public void CreateOrOpen_Multiple ()
{
MemoryMappedFile.CreateOrOpen (Path.Combine (tempDir, "createOrOpen.test"), 8192);
MemoryMappedFile.CreateOrOpen (Path.Combine (tempDir, "createOrOpen.test"), 8192);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CreateFromFileWithSmallerCapacityThanFile ()
{
var f = Path.Combine (tempDir, "8192-file");
File.WriteAllBytes (f, new byte [8192]);
// We are requesting fewer bytes to map.
MemoryMappedFile.CreateFromFile (f, FileMode.Open, "myMap", 4192);
}
[Test]
public void CreateFromFile_Null () {
AssertThrows<ArgumentNullException> (delegate () {
MemoryMappedFile.CreateFromFile (null);
});
}
[Test]
public void CreateViewStream_Offsets () {
var file = MemoryMappedFile.CreateFromFile (fname, FileMode.Open);
using (var stream = file.CreateViewStream (2, 3)) {
byte[] arr = new byte [128];
int len = stream.Read (arr, 0, 128);
Assert.AreEqual (3, len);
Assert.AreEqual ('l', (char)arr [0]);
Assert.AreEqual ('l', (char)arr [1]);
Assert.AreEqual ('o', (char)arr [2]);
}
}
[Test]
public void CreateViewStream_Rights () {
var file = MemoryMappedFile.CreateFromFile (fname, FileMode.Open);
using (var stream = file.CreateViewStream (0, 0, MemoryMappedFileAccess.Read)) {
AssertThrows<NotSupportedException> (delegate () {
stream.WriteByte (0);
});
}
using (var stream = file.CreateViewStream (0, 0, MemoryMappedFileAccess.Write)) {
AssertThrows<NotSupportedException> (delegate () {
stream.ReadByte ();
});
}
}
[Test]
public unsafe void CreateViewBasic () {
var file = MemoryMappedFile.CreateFromFile (fname, FileMode.Open);
using (var v = file.CreateViewAccessor ()) {
string s = "";
// FIXME: Use using
var handle = v.SafeMemoryMappedViewHandle;
byte *b = null;
try {
handle.AcquirePointer (ref b);
for (int i = 0; i < 5; ++i)
s += (char)b [i];
} finally {
handle.ReleasePointer ();
}
Assert.AreEqual ("Hello", s);
}
}
[Test]
public unsafe void ViewReadArray () {
var file = MemoryMappedFile.CreateFromFile (fname, FileMode.Open);
using (var v = file.CreateViewAccessor ()) {
var a = new byte [5];
var n = v.ReadArray (0, a, 0, 5);
Assert.AreEqual (5, n);
var s = new string (Array.ConvertAll (a, b => (char)b));
Assert.AreEqual ("Hello", s);
}
}
[Test]
public void NamedMappingToInvalidFile ()
{
var fileName = Path.Combine (tempDir, "temp_file_123");
if (File.Exists (fileName))
File.Delete (fileName);
var memoryMappedFile90 = MemoryMappedFile.CreateNew (fileName, 4194304, MemoryMappedFileAccess.ReadWrite);
memoryMappedFile90.CreateViewStream (4186112, 3222, MemoryMappedFileAccess.Write);
}
[Test]
public void CreateTheSameAreaTwiceShouldFail ()
{
var name = MkNamedMapping ();
using (var m0 = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWrite)) {
try {
using (var m1 = MemoryMappedFile.CreateNew (name, 4096, MemoryMappedFileAccess.ReadWrite)) {
Assert.Fail ("Must fail");
}
} catch (IOException) {}
}
}
[Test]
public void MapAFileToAMemoryAreaShouldFail ()
{
var name = MkNamedMapping ();
using (var m0 = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWrite)) {
try {
using (var m1 = MemoryMappedFile.CreateFromFile (fname, FileMode.OpenOrCreate, name)) {
Assert.Fail ("Must fail");
}
} catch (IOException) {}
}
}
[Test]
public void NamedMappingsShareMemoryArea ()
{
var name = MkNamedMapping ();
using (var m0 = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWrite)) {
using (var m1 = MemoryMappedFile.CreateOrOpen (name, 4096, MemoryMappedFileAccess.ReadWrite)) {
using (MemoryMappedViewAccessor v0 = m0.CreateViewAccessor (), v1 = m1.CreateViewAccessor ()) {
v0.Write (10, 0x12345);
Assert.AreEqual (0x12345, v1.ReadInt32 (10));
}
}
}
}
[Test]
public void NamedFileCanBeOpen ()
{
var name = MkNamedMapping ();
using (var sw = new FileStream (fname, FileMode.Open)) {
byte[] b = new byte[20];
for (int i = 0; i < 20; ++i)
b[i] = 0xFF;
sw.Write (b, 0, 20);
}
using (var m0 = MemoryMappedFile.CreateFromFile (fname, FileMode.Open, name)) {
using (var m1 = MemoryMappedFile.CreateOrOpen (name, 4096)) {
using (MemoryMappedViewAccessor v0 = m0.CreateViewAccessor (), v1 = m1.CreateViewAccessor ()) {
v0.Write (10, 0x11223344);
Assert.AreEqual (0x11223344, v1.ReadInt32 (10));
}
}
}
}
[Test]
public void MapAtEdgeOfPage ()
{
using (var f = new FileStream (fname, FileMode.Open)) {
var b = new byte [4096];
for (int i = 0; i < 4096; ++i)
b[i] = 0xAA;
for (int i = 0; i < 2; ++i)
f.Write (b, 0, 4096);
}
var m0 = MemoryMappedFile.CreateFromFile (fname, FileMode.Open);
var v0 = m0.CreateViewAccessor (500, 4096);
var v1 = m0.CreateViewAccessor (0, 4096 * 2);
for (int i = 0; i < 4096; ++i) {
Assert.AreEqual (0xAA, v1.ReadByte (i + 500));
v0.Write (i, (byte)0xFF);
Assert.AreEqual (0xFF, v1.ReadByte (i + 500));
}
}
[Test]
public void DoubleAccountingInOffsetCalculation ()
{
var memoryMappedFile90 = MemoryMappedFile.CreateNew (MkNamedMapping (), 4194304, MemoryMappedFileAccess.ReadWrite);
var stream = memoryMappedFile90.CreateViewStream (4186112, 3222, MemoryMappedFileAccess.Write);
using (var tw = new StreamWriter(stream))
{
tw.WriteLine ("Hello World!");
}
}
}
}
#endif

View File

@@ -0,0 +1,202 @@
// PipeSecurityTest.cs - NUnit Test Cases for PipeSecurity
//
// Authors:
// James Bellinger <jfb@zer7.com>
//
// Copyright (C) 2012 James Bellinger
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using NUnit.Framework;
namespace MonoTests.System.IO.Pipes
{
[TestFixture]
public class PipeSecurityTest
{
[Test]
public void NamedPipeDefaultPermissionsWork ()
{
if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
Assert.Ignore ();
}
string name = @"Local\MonoTestPipeNPNPW";
using (NamedPipeServerStream server = CreateNamedServer (false, name, null, 0)) {
PipeSecurity security = server.GetAccessControl ();
AuthorizationRuleCollection rules = security.GetAccessRules (true, false,
typeof (SecurityIdentifier));
Assert.AreNotEqual (0, rules.Count);
}
}
[Test]
public void NamedPipeSetAccessControlFailsWithoutChangePermissionRight ()
{
if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
Assert.Ignore ();
}
string name = @"Local\MonoTestPipeNPSACFWCPR";
using (NamedPipeServerStream server = CreateNamedServer (false, name, null, 0)) {
bool unauthorized = false;
try {
AddDenyEveryone (server);
} catch (UnauthorizedAccessException) {
unauthorized = true;
}
Assert.IsTrue (unauthorized, "PipeAccessRights.ChangePermissions was not required");
}
}
[Test]
public void NamedPipePermissionsActuallyWorkSyncAllow ()
{
NamedPipePermissionsActuallyWorkSync (@"Local\MonoTestPipeNPPAWSA", false);
}
[Test]
public void NamedPipePermissionsActuallyWorkSyncDeny ()
{
NamedPipePermissionsActuallyWorkSync (@"Local\MonoTestPipeNPPAWSD", true);
}
void NamedPipePermissionsActuallyWorkSync (string name, bool addDenyEveryone)
{
if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
Assert.Ignore ();
}
PipeSecurity security = new PipeSecurity ();
SecurityIdentifier worldSid = new SecurityIdentifier ("WD");
PipeAccessRule rule = new PipeAccessRule (worldSid,
PipeAccessRights.FullControl,
AccessControlType.Allow);
security.AddAccessRule (rule);
using (NamedPipeServerStream server = CreateNamedServer (false, name, security,
PipeAccessRights.ChangePermissions)) {
security = server.GetAccessControl ();
AuthorizationRuleCollection rules;
rules = security.GetAccessRules (true, true, typeof (SecurityIdentifier));
Assert.AreEqual (1, rules.Count);
rule = (PipeAccessRule)rules [0];
Assert.AreEqual (AccessControlType.Allow, rule.AccessControlType);
Assert.AreEqual (worldSid, rule.IdentityReference);
Assert.AreEqual (PipeAccessRights.FullControl, rule.PipeAccessRights);
if (addDenyEveryone)
AddDenyEveryone (server);
bool unauthorized = false;
using (NamedPipeClientStream client = CreateNamedClient (false, name)) {
try {
client.Connect (1000);
} catch (UnauthorizedAccessException) {
unauthorized = true;
}
}
Assert.AreEqual (addDenyEveryone, unauthorized);
}
}
[Test]
[Category ("NotWorking")] // Async is completely broken on Mono Win32 pipes.
public void NamedPipePermissionsActuallyWorkAsync ()
{
if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
Assert.Ignore ();
}
IAsyncResult waitForConnection;
string name = @"Local\MonoTestPipeNPPAWA";
using (NamedPipeServerStream server = CreateNamedServer (true, name, null,
PipeAccessRights.ChangePermissions)) {
// Test connecting to make sure our later test throwing is due to permissions.
waitForConnection = server.BeginWaitForConnection (null, null);
using (NamedPipeClientStream client = CreateNamedClient (true, name)) {
client.Connect (1000);
if (!waitForConnection.AsyncWaitHandle.WaitOne (1000)) {
Assert.Fail ("No connection request received."); return;
}
server.EndWaitForConnection (waitForConnection);
server.Disconnect ();
}
// Let's add a Deny for Everyone.
AddDenyEveryone (server);
// This Connect call should fail.
waitForConnection = server.BeginWaitForConnection (null, null);
bool unauthorized = false;
using (NamedPipeClientStream client = CreateNamedClient (true, name)) {
try {
client.Connect (1000);
} catch (UnauthorizedAccessException) {
unauthorized = true;
}
}
Assert.IsTrue (unauthorized, "Client was allowed to connect despite Deny ACE.");
}
}
static void AddDenyEveryone (PipeStream stream)
{
PipeAccessRule rule; PipeSecurity security;
AuthorizationRuleCollection inRules, outRules;
// Let's add a Deny for Everyone.
security = stream.GetAccessControl ();
inRules = security.GetAccessRules (true, false, typeof (SecurityIdentifier));
Assert.AreNotEqual (0, inRules.Count);
rule = new PipeAccessRule (new SecurityIdentifier ("WD"),
PipeAccessRights.FullControl,
AccessControlType.Deny);
security.AddAccessRule (rule);
stream.SetAccessControl (security);
security = stream.GetAccessControl ();
outRules = security.GetAccessRules (true, false, typeof (SecurityIdentifier));
Assert.AreEqual (inRules.Count + 1, outRules.Count);
}
static NamedPipeClientStream CreateNamedClient (bool @async, string name)
{
return new NamedPipeClientStream (".", name,
PipeDirection.InOut,
@async ? PipeOptions.Asynchronous : PipeOptions.None);
}
static NamedPipeServerStream CreateNamedServer (bool @async, string name,
PipeSecurity security,
PipeAccessRights additionalRights)
{
return new NamedPipeServerStream (name,
PipeDirection.InOut, 1,
PipeTransmissionMode.Byte,
@async ? PipeOptions.Asynchronous : PipeOptions.None,
512, 512, security,
HandleInheritability.None,
additionalRights);
}
}
}

View File

@@ -0,0 +1,132 @@
2010-05-19 Jb Evain <jbevain@novell.com>
* ExpressionTest_Constant.cs: add tests for nullable constants.
2009-09-03 Jb Evain <jbevain@novell.com>
* ExpressionTest_Constant.cs: add test to emit dbnull constants.
2009-09-03 Jb Evain <jbevain@novell.com>
* ExpressionTest_Constant.cs: add test to emit DateTime constants.
2009-07-07 Raja R Harinath <harinath@hurrynot.org>
* ExpressionTest.cs (ExpressionDelegateTarget) [NET_4_0]: Disable
check for ExecutionScope.
(GlobalsInSpace) [NET_4_0]: Disable.
2008-09-22 Jb Evain <jbevain@novell.com>
* ExpressionTest_TypeIs.cs: add test for bug #428309.
2008-05-13 Roei Erez <roeie@mainsoft.com>
* ExpressionTest.cs: Exclude tests only in JAVAEE environment.
2008-03-05 Jb Evain <jbevain@novell.com>
* ExpressionTest_Call.cs: we pass the Call with type arguments tests.
2008-02-24 Jb Evain <jbevain@novell.com>
* ExpressionTest.cs: test for Action compilation.
2008-02-04 Jb Evain <jbevain@novell.com>
* ExpressionTest_ListBind.cs: add working test for MemberListBinding
ToStringification.
2008-02-02 Jb Evain <jbevain@novell.com>
* ExpressionTest_ListBind.cs: fix MemberTypeImplementIEnumerable test.
2008-02-01 Olivier Dufour <olivier.duff@gmail.com>
* ExpressionTest_ListBind.cs:Add test for ListBind
2008-02-01 Olivier Dufour <olivier.duff@gmail.com>
* ExpressionTest_ElementInit.cs:Add test for ElementInit
2008-01-31 Jb Evain <jbevain@novell.com>
* ExpressionTest_ArrayLength.cs: add compile test.
2008-01-31 Jb Evain <jbevain@novell.com>
* ExpressionTest_Field.cs: add field access tests.
2008-01-30 Jb Evain <jbevain@novell.com>
* ExpressionTest_CallWithExpression.cs: add tests for very simple calls.
2008-01-30 Jb Evain <jbevain@novell.com>
* ExpressionTest_New.cs: add tests for emitting new reference types.
2008-01-27 Jb Evain <jbevain@novell.com>
* ExpressionTest_Condition.cs: tests for compilation of
conditionals.
2008-01-27 Jb Evain <jbevain@novell.com>
* ExpressionTest_Lambda.cs: add test for the
Lambda(Expression,ParameterExpression[]) method.
2008-01-27 Jb Evain <jbevain@novell.com>
* ExpressionTest_Lambda.cs: add tests to assert the type
of the LambdaExpressions.
2008-01-18 Jb Evain <jbevain@novell.com>
* ExpressionTest_GreaterThan|GreaterThanOrEqual.cs
* ExpressionTest_LessThan|LessThanOrEqual.cs: new tests.
2008-01-18 Jb Evain <jbevain@novell.com>
* ExpressionTest_Negate.cs
ExpressionTest_Not.cs
ExpressionTest_UnaryPlus.cs: test for some unary operators.
2008-01-16 Jb Evain <jbevain@novell.com>
* ExpressionTest_CallWithExpression.cs: test for static method.
2008-01-15 Jb Evain <jbevain@novell.com>
* ExpressionTest_CallWithExpression.cs: tests
for Call (Expression, ...)
2008-01-15 Jb Evain <jbevain@novell.com>
* ExpressionTest_Condition.cs: add tests for Expression.Condition.
2008-01-15 Jb Evain <jbevain@novell.com>
* ExpressionTest.cs: tests for Expression.Parameter
2008-01-09 Jb Evain <jbevain@novell.com>
* ExpressionTest.cs: tests for GetActionType.
2008-01-09 Jb Evain <jbevain@novell.com>
* ExpressionTest.cs: add new fixture of assorted tests for
Expression. Contains tests for GetFuncType for now.
2008-01-09 Jb Evain <jbevain@novell.com>
* ExpressionTest_ArrayLength.cs: Fix Rank2String to pass on .net.
2008-01-09 Jb Evain <jbevain@novell.com>
* ExpressionTest_Call.cs: fix wrong test.
2008-01-09 Jb Evain <jbevain@novell.com>
* ExpressionTest_TypeAs.cs: correct wrong test for numerics.
Add test for nullable types.

View File

@@ -0,0 +1,309 @@
//
// ExpressionTest.cs
//
// Author:
// Jb Evain (jbevain@novell.com)
//
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions {
[TestFixture]
public class ExpressionTest {
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetFuncTypeArgNull ()
{
Expression.GetFuncType (null);
}
static Type [] GetTestTypeArray (int length)
{
return Enumerable.Range (0, length - 1)
.Select (i => typeof (int))
.ToArray ();
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetFuncTypeArgEmpty ()
{
Expression.GetFuncType (Type.EmptyTypes);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetFuncTypeArgTooBig ()
{
Expression.GetFuncType (GetTestTypeArray (64));
}
[Test]
public void GetFuncTypeTest ()
{
var func = Expression.GetFuncType (new [] {typeof (int)});
Assert.AreEqual (typeof (Func<int>), func);
func = Expression.GetFuncType (new [] {typeof (int), typeof (int)});
Assert.AreEqual (typeof (Func<int, int>), func);
func = Expression.GetFuncType (new [] {typeof (int), typeof (int), typeof (int)});
Assert.AreEqual (typeof (Func<int, int, int>), func);
func = Expression.GetFuncType (new [] {typeof (int), typeof (int), typeof (int), typeof (int)});
Assert.AreEqual (typeof (Func<int, int, int, int>), func);
func = Expression.GetFuncType (new [] {typeof (int), typeof (int), typeof (int), typeof (int), typeof (int)});
Assert.AreEqual (typeof (Func<int, int, int, int, int>), func);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetActionTypeArgNull ()
{
Expression.GetActionType (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetActionTypeArgTooBig ()
{
Expression.GetActionType (GetTestTypeArray (45));
}
[Test]
public void GetActionTypeTest ()
{
var action = Expression.GetActionType (new Type [0]);
Assert.AreEqual (typeof (Action), action);
action = Expression.GetActionType (new [] {typeof (int)});
Assert.AreEqual (typeof (Action<int>), action);
action = Expression.GetActionType (new [] {typeof (int), typeof (int)});
Assert.AreEqual (typeof (Action<int, int>), action);
action = Expression.GetActionType (new [] {typeof (int), typeof (int), typeof (int)});
Assert.AreEqual (typeof (Action<int, int, int>), action);
action = Expression.GetActionType (new [] {typeof (int), typeof (int), typeof (int), typeof (int)});
Assert.AreEqual (typeof (Action<int, int, int, int>), action);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void ParameterNullType ()
{
Expression.Parameter (null, "foo");
}
[Test]
public void ParameterNullName ()
{
var p = Expression.Parameter (typeof (string), null);
Assert.AreEqual (null, p.Name);
Assert.AreEqual (typeof (string), p.Type);
#if !NET_4_0
Assert.AreEqual ("<param>", p.ToString ());
#endif
}
[Test]
public void ParameterEmptyName ()
{
var p = Expression.Parameter (typeof (string), "");
Assert.AreEqual ("", p.Name);
Assert.AreEqual (typeof (string), p.Type);
#if !NET_4_0
Assert.AreEqual ("", p.ToString ());
#endif
}
[Test]
public void Parameter ()
{
var p = Expression.Parameter (typeof (string), "foo");
Assert.AreEqual ("foo", p.Name);
Assert.AreEqual (typeof (string), p.Type);
Assert.AreEqual ("foo", p.ToString ());
}
[Test]
[Category ("NotDotNet")]
[ExpectedException (typeof (ArgumentException))]
public void VoidParameter ()
{
Expression.Parameter (typeof (void), "hello");
}
static int buffer;
public static int Identity (int i)
{
buffer = i;
return i;
}
[Test]
public void CompileActionDiscardingRetValue ()
{
var p = Expression.Parameter (typeof (int), "i");
var identity = GetType ().GetMethod ("Identity", BindingFlags.Static | BindingFlags.Public );
Assert.IsNotNull (identity);
var lambda = Expression.Lambda<Action<int>> (Expression.Call (identity, p), p);
var method = lambda.Compile ();
buffer = 0;
method (42);
Assert.AreEqual (42, buffer);
}
[Test]
[Category("TargetJvmNotSupported")]
public void ExpressionDelegateTarget ()
{
var p = Expression.Parameter (typeof (string), "str");
var identity = Expression.Lambda<Func<string, string>> (p, p).Compile ();
Assert.AreEqual (typeof (Func<string, string>), identity.GetType ());
Assert.IsNotNull (identity.Target);
#if !NET_4_0
Assert.AreEqual (typeof (ExecutionScope), identity.Target.GetType ());
#endif
}
class Foo {
public string gazonk;
}
struct Bar {
public int baz;
public override string ToString ()
{
return baz.ToString ();
}
}
#if !NET_4_0
[Test]
[Category ("TargetJvmNotSupported")]
public void GlobalsInScope ()
{
var foo = new Foo { gazonk = "gazonk" };
var bar = new Bar { baz = 42 };
var l = Expression.Lambda<Func<string>> (
Expression.Call (
typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }),
Expression.Field (Expression.Constant (foo), typeof (Foo).GetField ("gazonk")),
Expression.Call (Expression.Constant (bar), typeof (Bar).GetMethod ("ToString"))));
var del = l.Compile ();
var scope = del.Target as ExecutionScope;
Assert.IsNotNull (scope);
var globals = scope.Globals;
Assert.IsNotNull (globals);
Assert.AreEqual (2, globals.Length);
Assert.AreEqual (typeof (StrongBox<Foo>), globals [0].GetType ());
Assert.AreEqual (typeof (StrongBox<Bar>), globals [1].GetType ());
Assert.AreEqual (foo, ((StrongBox<Foo>) globals [0]).Value);
Assert.AreEqual (bar, ((StrongBox<Bar>) globals [1]).Value);
Assert.AreEqual ("gazonk42", del ());
}
#endif
[Test]
public void SimpleHoistedParameter ()
{
var p = Expression.Parameter (typeof (string), "s");
var f = Expression.Lambda<Func<string, Func<string>>> (
Expression.Lambda<Func<string>> (
p,
new ParameterExpression [0]),
p).Compile ();
var f2 = f ("x");
Assert.AreEqual ("x", f2 ());
}
[Test]
public void TwoHoistingLevels ()
{
var p1 = Expression.Parameter (typeof (string), "x");
var p2 = Expression.Parameter (typeof (string), "y");
Expression<Func<string, Func<string, Func<string>>>> e =
Expression.Lambda<Func<string, Func<string, Func<string>>>> (
Expression.Lambda<Func<string, Func<string>>> (
Expression.Lambda<Func<string>> (
Expression.Call (
typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }),
new [] { p1, p2 }),
new ParameterExpression [0]),
new [] { p2 }),
new [] { p1 });
var f = e.Compile ();
var f2 = f ("Hello ");
var f3 = f2 ("World !");
Assert.AreEqual ("Hello World !", f3 ());
}
[Test]
public void HoistedParameter ()
{
var i = Expression.Parameter (typeof (int), "i");
var l = Expression.Lambda<Func<int, string>> (
Expression.Invoke (
Expression.Lambda<Func<string>> (
Expression.Call (i, typeof (int).GetMethod ("ToString", Type.EmptyTypes)))), i).Compile ();
Assert.AreEqual ("42", l (42));
}
}
}

View File

@@ -0,0 +1,402 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
// Jb Evain <jbevain@novell.com>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Add
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Add (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.Add (Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void ArgTypesDifferent ()
{
Expression.Add (Expression.Constant (1), Expression.Constant (2.0));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void NoOperatorClass ()
{
Expression.Add (Expression.Constant (new NoOpClass ()), Expression.Constant (new NoOpClass ()));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void Boolean ()
{
Expression.Add (Expression.Constant (true), Expression.Constant (false));
}
[Test]
public void Numeric ()
{
BinaryExpression expr = Expression.Add (Expression.Constant (1), Expression.Constant (2));
Assert.AreEqual (ExpressionType.Add, expr.NodeType, "Add#01");
Assert.AreEqual (typeof (int), expr.Type, "Add#02");
Assert.IsNull (expr.Method, "Add#03");
Assert.AreEqual ("(1 + 2)", expr.ToString(), "Add#04");
}
[Test]
public void Nullable ()
{
int? a = 1;
int? b = 2;
BinaryExpression expr = Expression.Add (Expression.Constant (a,typeof(int?)),
Expression.Constant (b, typeof(int?)));
Assert.AreEqual (ExpressionType.Add, expr.NodeType, "Add#05");
Assert.AreEqual (typeof (int?), expr.Type, "Add#06");
Assert.IsNull (expr.Method, "Add#07");
Assert.AreEqual ("(1 + 2)", expr.ToString(), "Add#08");
}
[Test]
public void UserDefinedClass ()
{
// We can use the simplest version of GetMethod because we already know only one
// exists in the very simple class we're using for the tests.
MethodInfo mi = typeof (OpClass).GetMethod ("op_Addition");
OpClass left = new OpClass ();
BinaryExpression expr = Expression.Add (Expression.Constant (left), Expression.Constant (new OpClass ()));
Assert.AreEqual (ExpressionType.Add, expr.NodeType, "Add#09");
Assert.AreEqual (typeof (OpClass), expr.Type, "Add#10");
Assert.AreEqual (mi, expr.Method, "Add#11");
Assert.AreEqual ("op_Addition", expr.Method.Name, "Add#12");
Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) + value(MonoTests.System.Linq.Expressions.OpClass))",
expr.ToString(), "Add#13");
Expression.Lambda<Func<OpClass>> (expr);
#if false
//
// We do not have support for objects that are not really
// constants, like this case. Need to figure out what to do
// with those
//
Func<OpClass> compiled = l.Compile ();
Assert.AreEqual (left, compiled ());
#endif
}
public class S {
public static int MyAdder (int a, int b){
return 1000;
}
}
[Test]
public void TestMethodAddition ()
{
BinaryExpression expr = Expression.Add (Expression.Constant (1), Expression.Constant (2), typeof(S).GetMethod("MyAdder"));
Expression<Func<int>> l = Expression.Lambda<Func<int>> (expr);
Func<int> compiled = l.Compile ();
Assert.AreEqual (1000, compiled ());
}
[Test]
public void CompileAdd ()
{
var left = Expression.Parameter (typeof (int), "l");
var right = Expression.Parameter (typeof (int), "r");
var l = Expression.Lambda<Func<int, int, int>> (
Expression.Add (left, right), left, right);
var be = l.Body as BinaryExpression;
Assert.IsNotNull (be);
Assert.AreEqual (typeof (int), be.Type);
Assert.IsFalse (be.IsLifted);
Assert.IsFalse (be.IsLiftedToNull);
var add = l.Compile ();
Assert.AreEqual (12, add (6, 6));
Assert.AreEqual (0, add (-1, 1));
Assert.AreEqual (-2, add (1, -3));
}
[Test]
public void AddLifted ()
{
var b = Expression.Add (
Expression.Constant (null, typeof (int?)),
Expression.Constant (null, typeof (int?)));
Assert.AreEqual (typeof (int?), b.Type);
Assert.IsTrue (b.IsLifted);
Assert.IsTrue (b.IsLiftedToNull);
}
[Test]
public void AddNotLifted ()
{
var b = Expression.Add (
Expression.Constant (1, typeof (int)),
Expression.Constant (1, typeof (int)));
Assert.AreEqual (typeof (int), b.Type);
Assert.IsFalse (b.IsLifted);
Assert.IsFalse (b.IsLiftedToNull);
}
[Test]
[Category ("NotWorkingInterpreter")]
public void AddTestNullable ()
{
var a = Expression.Parameter (typeof (int?), "a");
var b = Expression.Parameter (typeof (int?), "b");
var l = Expression.Lambda<Func<int?, int?, int?>> (
Expression.Add (a, b), a, b);
var be = l.Body as BinaryExpression;
Assert.IsNotNull (be);
Assert.AreEqual (typeof (int?), be.Type);
Assert.IsTrue (be.IsLifted);
Assert.IsTrue (be.IsLiftedToNull);
var c = l.Compile ();
Assert.AreEqual (null, c (1, null), "a1");
Assert.AreEqual (null, c (null, null), "a2");
Assert.AreEqual (null, c (null, 2), "a3");
Assert.AreEqual (3, c (1, 2), "a4");
}
struct Slot {
public int Value;
public Slot (int value)
{
this.Value = value;
}
public static Slot operator + (Slot a, Slot b)
{
return new Slot (a.Value + b.Value);
}
}
[Test]
public void UserDefinedAdd ()
{
var l = Expression.Parameter (typeof (Slot), "l");
var r = Expression.Parameter (typeof (Slot), "r");
var node = Expression.Add (l, r);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
Assert.AreEqual (typeof (Slot), node.Type);
var add = Expression.Lambda<Func<Slot, Slot, Slot>> (node, l, r).Compile ();
Assert.AreEqual (new Slot (42), add (new Slot (21), new Slot (21)));
Assert.AreEqual (new Slot (0), add (new Slot (1), new Slot (-1)));
}
[Test]
[Category ("NotWorkingInterpreter")]
public void UserDefinedAddLifted ()
{
var l = Expression.Parameter (typeof (Slot?), "l");
var r = Expression.Parameter (typeof (Slot?), "r");
var node = Expression.Add (l, r);
Assert.IsTrue (node.IsLifted);
Assert.IsTrue (node.IsLiftedToNull);
Assert.AreEqual (typeof (Slot?), node.Type);
var add = Expression.Lambda<Func<Slot?, Slot?, Slot?>> (node, l, r).Compile ();
Assert.AreEqual (null, add (null, null));
Assert.AreEqual ((Slot?) new Slot (42), add ((Slot?) new Slot (21), (Slot?) new Slot (21)));
}
struct SlotToNullable {
public int Value;
public SlotToNullable (int value)
{
this.Value = value;
}
public static SlotToNullable? operator + (SlotToNullable a, SlotToNullable b)
{
return new SlotToNullable (a.Value + b.Value);
}
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void UserDefinedToNullableAddFromNullable ()
{
Expression.Add (
Expression.Parameter (typeof (SlotToNullable?), "l"),
Expression.Parameter (typeof (SlotToNullable?), "r"));
}
[Test]
public void UserDefinedToNullableAdd ()
{
var l = Expression.Parameter (typeof (SlotToNullable), "l");
var r = Expression.Parameter (typeof (SlotToNullable), "r");
var node = Expression.Add (l, r);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
Assert.AreEqual (typeof (SlotToNullable?), node.Type);
Assert.IsNotNull (node.Method);
var add = Expression.Lambda<Func<SlotToNullable, SlotToNullable, SlotToNullable?>> (node, l, r).Compile ();
Assert.AreEqual ((SlotToNullable?) new SlotToNullable (4), add (new SlotToNullable (2), new SlotToNullable (2)));
Assert.AreEqual ((SlotToNullable?) new SlotToNullable (0), add (new SlotToNullable (2), new SlotToNullable (-2)));
}
/*struct SlotFromNullableToNullable {
public int Value;
public SlotFromNullableToNullable (int value)
{
this.Value = value;
}
public static SlotFromNullableToNullable? operator + (SlotFromNullableToNullable? a, SlotFromNullableToNullable? b)
{
if (a.HasValue && b.HasValue)
return (SlotFromNullableToNullable?) new SlotFromNullableToNullable (
a.Value.Value + b.Value.Value);
else
return null;
}
}
[Test]
public void UserDefinedFromNullableToNullableAdd ()
{
var l = Expression.Parameter (typeof (SlotFromNullableToNullable?), "l");
var r = Expression.Parameter (typeof (SlotFromNullableToNullable?), "r");
var node = Expression.Add (l, r);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
Assert.AreEqual (typeof (SlotFromNullableToNullable?), node.Type);
Assert.IsNotNull (node.Method);
var add = Expression.Lambda<Func<SlotFromNullableToNullable?, SlotFromNullableToNullable?, SlotFromNullableToNullable?>> (node, l, r).Compile ();
Assert.AreEqual ((SlotFromNullableToNullable?) null, add (null, null));
Assert.AreEqual ((SlotFromNullableToNullable?) null, add (new SlotFromNullableToNullable (2), null));
Assert.AreEqual ((SlotFromNullableToNullable?) null, add (null, new SlotFromNullableToNullable (2)));
Assert.AreEqual ((SlotFromNullableToNullable?) new SlotFromNullableToNullable (4), add (new SlotFromNullableToNullable (2), new SlotFromNullableToNullable (2)));
Assert.AreEqual ((SlotFromNullableToNullable?) new SlotFromNullableToNullable (0), add (new SlotFromNullableToNullable (2), new SlotFromNullableToNullable (-2)));
}*/
[Test]
public void AddStrings ()
{
var l = Expression.Parameter (typeof (string), "l");
var r = Expression.Parameter (typeof (string), "r");
var meth = typeof (string).GetMethod ("Concat", new [] { typeof (object), typeof (object) });
var node = Expression.Add (l, r, meth);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
Assert.AreEqual (typeof (string), node.Type);
Assert.AreEqual (meth, node.Method);
var concat = Expression.Lambda<Func<string, string, string>> (node, l, r).Compile ();
Assert.AreEqual (string.Empty, concat (null, null));
Assert.AreEqual ("foobar", concat ("foo", "bar"));
}
[Test]
public void AddDecimals ()
{
var l = Expression.Parameter (typeof (decimal), "l");
var r = Expression.Parameter (typeof (decimal), "r");
var meth = typeof (decimal).GetMethod ("op_Addition", new [] { typeof (decimal), typeof (decimal) });
var node = Expression.Add (l, r);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
Assert.AreEqual (typeof (decimal), node.Type);
Assert.AreEqual (meth, node.Method);
var add = Expression.Lambda<Func<decimal, decimal, decimal>> (node, l, r).Compile ();
Assert.AreEqual (2m, add (1m, 1m));
}
[Test]
[Category ("NotWorkingInterpreter")]
public void AddLiftedDecimals ()
{
var l = Expression.Parameter (typeof (decimal?), "l");
var r = Expression.Parameter (typeof (decimal?), "r");
var meth = typeof (decimal).GetMethod ("op_Addition", new [] { typeof (decimal), typeof (decimal) });
var node = Expression.Add (l, r);
Assert.IsTrue (node.IsLifted);
Assert.IsTrue (node.IsLiftedToNull);
Assert.AreEqual (typeof (decimal?), node.Type);
Assert.AreEqual (meth, node.Method);
var add = Expression.Lambda<Func<decimal?, decimal?, decimal?>> (node, l, r).Compile ();
Assert.AreEqual (2m, add (1m, 1m));
Assert.AreEqual (null, add (1m, null));
Assert.AreEqual (null, add (null, null));
}
}
}

View File

@@ -0,0 +1,208 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_AddChecked
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.AddChecked (null, Expression.Constant(1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.AddChecked (Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void ArgTypesDifferent ()
{
Expression.AddChecked (Expression.Constant (1), Expression.Constant (2.0));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void NoOperatorClass ()
{
Expression.AddChecked (Expression.Constant (new NoOpClass ()), Expression.Constant (new NoOpClass ()));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void Boolean ()
{
Expression.AddChecked (Expression.Constant (true), Expression.Constant (false));
}
[Test]
public void Numeric ()
{
BinaryExpression expr = Expression.AddChecked (Expression.Constant (1), Expression.Constant (2));
Assert.AreEqual (ExpressionType.AddChecked, expr.NodeType, "AddChecked#01");
Assert.AreEqual (typeof (int), expr.Type, "AddChecked#02");
Assert.IsNull (expr.Method, "AddChecked#03");
Assert.AreEqual ("(1 + 2)", expr.ToString(), "AddChecked#15");
}
[Test]
public void Nullable ()
{
int? a = 1;
int? b = 2;
BinaryExpression expr = Expression.AddChecked (Expression.Constant (a), Expression.Constant (b));
Assert.AreEqual (ExpressionType.AddChecked, expr.NodeType, "AddChecked#04");
Assert.AreEqual (typeof (int), expr.Type, "AddChecked#05");
Assert.IsNull (expr.Method, null, "AddChecked#06");
Assert.AreEqual ("(1 + 2)", expr.ToString(), "AddChecked#16");
}
[Test]
public void UserDefinedClass ()
{
// We can use the simplest version of GetMethod because we already know only one
// exists in the very simple class we're using for the tests.
MethodInfo mi = typeof (OpClass).GetMethod ("op_Addition");
BinaryExpression expr = Expression.AddChecked (Expression.Constant (new OpClass ()), Expression.Constant (new OpClass ()));
Assert.AreEqual (ExpressionType.AddChecked, expr.NodeType, "AddChecked#07");
Assert.AreEqual (typeof (OpClass), expr.Type, "AddChecked#08");
Assert.AreEqual (mi, expr.Method, "AddChecked#09");
Assert.AreEqual ("op_Addition", expr.Method.Name, "AddChecked#10");
Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) + value(MonoTests.System.Linq.Expressions.OpClass))",
expr.ToString(), "AddChecked#17");
}
[Test]
public void UserDefinedStruct ()
{
// We can use the simplest version of GetMethod because we already know only one
// exists in the very simple class we're using for the tests.
MethodInfo mi = typeof (OpStruct).GetMethod ("op_Addition");
BinaryExpression expr = Expression.AddChecked (Expression.Constant (new OpStruct ()), Expression.Constant (new OpStruct ()));
Assert.AreEqual (ExpressionType.AddChecked, expr.NodeType, "AddChecked#11");
Assert.AreEqual (typeof (OpStruct), expr.Type, "AddChecked#12");
Assert.AreEqual (mi, expr.Method, "AddChecked#13");
Assert.AreEqual ("op_Addition", expr.Method.Name, "AddChecked#14");
Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpStruct) + value(MonoTests.System.Linq.Expressions.OpStruct))",
expr.ToString(), "AddChecked#18");
}
//
// This method makes sure that compiling an AddChecked on two values
// throws an OverflowException, if it doesnt, it fails
//
static void MustOverflow<T> (T v1, T v2)
{
Expression<Func<T>> l = Expression.Lambda<Func<T>> (
Expression.AddChecked (Expression.Constant (v1), Expression.Constant (v2)));
Func<T> del = l.Compile ();
T res = default (T);
try {
res = del ();
} catch (OverflowException){
// OK
return;
}
throw new Exception (String.Format ("AddChecked on {2} should have thrown an exception with values {0} {1}, result was: {3}",
v1, v2, v1.GetType (), res));
}
//
// This routine should execute the code, but not throw an
// overflow exception
//
static void MustNotOverflow<T> (T v1, T v2)
{
Expression<Func<T>> l = Expression.Lambda<Func<T>> (
Expression.AddChecked (Expression.Constant (v1), Expression.Constant (v2)));
Func<T> del = l.Compile ();
del ();
}
//
// SubtractChecked is not defined for small types (byte, sbyte)
//
static void InvalidOperation<T> (T v1, T v2)
{
try {
Expression.Lambda<Func<T>> (
Expression.AddChecked (Expression.Constant (v1), Expression.Constant (v2)));
} catch (InvalidOperationException){
// OK
return;
}
throw new Exception (String.Format ("AddChecked should have thrown for the creation of a tree with {0} operands", v1.GetType ()));
}
[Test]
public void TestOverflows ()
{
// These should overflow, check the various types and codepaths
// in BinaryExpression:
MustOverflow<int> (Int32.MaxValue, 1);
MustOverflow<int> (Int32.MinValue, -11);
MustOverflow<long> (Int64.MaxValue, 1);
MustOverflow<long> (Int64.MinValue, -1);
// unsigned values use Add_Ovf_Un, check that too:
MustOverflow<ulong> (UInt64.MaxValue, 1);
MustOverflow<uint> (UInt32.MaxValue, 1);
}
//
// These should not overflow
//
[Test]
public void TestNoOverflow ()
{
// Simple stuff
MustNotOverflow<int> (10, 20);
// These are invalid:
InvalidOperation<byte> (Byte.MaxValue, 2);
InvalidOperation<sbyte> (SByte.MaxValue, 2);
#if !NET_4_0
// Stuff that just fits in 32 bits, does not overflow:
MustNotOverflow<short> (Int16.MaxValue, 2);
MustNotOverflow<short> (Int16.MaxValue, 2);
MustNotOverflow<ushort> (UInt16.MaxValue, 2);
#endif
// Doubles, floats, do not overflow
MustNotOverflow<float> (Single.MaxValue, 1);
MustNotOverflow<double> (Double.MaxValue, 1);
}
}
}

View File

@@ -0,0 +1,231 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
// Jb Evain <jbevain@novell.com>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_And
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.And (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.And (Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void NoOperatorClass ()
{
Expression.And (Expression.Constant (new NoOpClass ()), Expression.Constant (new NoOpClass ()));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void ArgTypesDifferent ()
{
Expression.And (Expression.Constant (1), Expression.Constant (true));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void Double ()
{
Expression.And (Expression.Constant (1.0), Expression.Constant (2.0));
}
[Test]
public void Integer ()
{
BinaryExpression expr = Expression.And (Expression.Constant (1), Expression.Constant (2));
Assert.AreEqual (ExpressionType.And, expr.NodeType, "And#01");
Assert.AreEqual (typeof (int), expr.Type, "And#02");
Assert.IsNull (expr.Method, "And#03");
Assert.AreEqual ("(1 & 2)", expr.ToString(), "And#04");
}
[Test]
public void Boolean ()
{
BinaryExpression expr = Expression.And (Expression.Constant (true), Expression.Constant (false));
Assert.AreEqual (ExpressionType.And, expr.NodeType, "And#05");
Assert.AreEqual (typeof (bool), expr.Type, "And#06");
Assert.IsNull (expr.Method, "And#07");
Assert.AreEqual ("(True And False)", expr.ToString(), "And#08");
}
[Test]
public void UserDefinedClass ()
{
// We can use the simplest version of GetMethod because we already know only one
// exists in the very simple class we're using for the tests.
MethodInfo mi = typeof (OpClass).GetMethod ("op_BitwiseAnd");
BinaryExpression expr = Expression.And (Expression.Constant (new OpClass ()), Expression.Constant (new OpClass ()));
Assert.AreEqual (ExpressionType.And, expr.NodeType, "And#09");
Assert.AreEqual (typeof (OpClass), expr.Type, "And#10");
Assert.AreEqual (mi, expr.Method, "And#11");
Assert.AreEqual ("op_BitwiseAnd", expr.Method.Name, "And#12");
Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) & value(MonoTests.System.Linq.Expressions.OpClass))",
expr.ToString(), "And#13");
}
[Test]
public void AndBoolTest ()
{
var a = Expression.Parameter (typeof (bool), "a");
var b = Expression.Parameter (typeof (bool), "b");
var l = Expression.Lambda<Func<bool, bool, bool>> (
Expression.And (a, b), a, b);
var be = l.Body as BinaryExpression;
Assert.IsNotNull (be);
Assert.AreEqual (typeof (bool), be.Type);
Assert.IsFalse (be.IsLifted);
Assert.IsFalse (be.IsLiftedToNull);
var c = l.Compile ();
Assert.AreEqual (true, c (true, true), "t1");
Assert.AreEqual (false, c (true, false), "t2");
Assert.AreEqual (false, c (false, true), "t3");
Assert.AreEqual (false, c (false, false), "t4");
}
[Test]
public void AndLifted ()
{
var b = Expression.And (
Expression.Constant (null, typeof (bool?)),
Expression.Constant (null, typeof (bool?)));
Assert.AreEqual (typeof (bool?), b.Type);
Assert.IsTrue (b.IsLifted);
Assert.IsTrue (b.IsLiftedToNull);
}
[Test]
public void AndBoolNullableTest ()
{
var a = Expression.Parameter (typeof (bool?), "a");
var b = Expression.Parameter (typeof (bool?), "b");
var l = Expression.Lambda<Func<bool?, bool?, bool?>> (
Expression.And (a, b), a, b);
var be = l.Body as BinaryExpression;
Assert.IsNotNull (be);
Assert.AreEqual (typeof (bool?), be.Type);
Assert.IsTrue (be.IsLifted);
Assert.IsTrue (be.IsLiftedToNull);
var c = l.Compile ();
Assert.AreEqual (true, c (true, true), "a1");
Assert.AreEqual (false, c (true, false), "a2");
Assert.AreEqual (false, c (false, true), "a3");
Assert.AreEqual (false, c (false, false), "a4");
Assert.AreEqual (null, c (true, null), "a5");
Assert.AreEqual (false, c (false, null), "a6");
Assert.AreEqual (false, c (null, false), "a7");
Assert.AreEqual (null, c (true, null), "a8");
Assert.AreEqual (null, c (null, null), "a9");
}
[Test]
public void AndBoolItem ()
{
var i = Expression.Parameter (typeof (Item<bool>), "i");
var and = Expression.Lambda<Func<Item<bool>, bool>> (
Expression.And (
Expression.Property (i, "Left"),
Expression.Property (i, "Right")), i).Compile ();
var item = new Item<bool> (false, true);
Assert.AreEqual (false, and (item));
Assert.IsTrue (item.LeftCalled);
Assert.IsTrue (item.RightCalled);
}
[Test]
public void AndNullableBoolItem ()
{
var i = Expression.Parameter (typeof (Item<bool?>), "i");
var and = Expression.Lambda<Func<Item<bool?>, bool?>> (
Expression.And (
Expression.Property (i, "Left"),
Expression.Property (i, "Right")), i).Compile ();
var item = new Item<bool?> (false, true);
Assert.AreEqual ((bool?) false, and (item));
Assert.IsTrue (item.LeftCalled);
Assert.IsTrue (item.RightCalled);
}
[Test]
public void AndIntTest ()
{
var a = Expression.Parameter (typeof (int), "a");
var b = Expression.Parameter (typeof (int), "b");
var and = Expression.Lambda<Func<int, int, int>> (
Expression.And (a, b), a, b).Compile ();
Assert.AreEqual (0, and (0, 0), "t1");
Assert.AreEqual (0, and (0, 1), "t2");
Assert.AreEqual (0, and (1, 0), "t3");
Assert.AreEqual (1, and (1, 1), "t4");
}
[Test]
public void AndIntNullableTest ()
{
var a = Expression.Parameter (typeof (int?), "a");
var b = Expression.Parameter (typeof (int?), "b");
var c = Expression.Lambda<Func<int?, int?, int?>> (
Expression.And (a, b), a, b).Compile ();
Assert.AreEqual ((int?) 1, c (1, 1), "a1");
Assert.AreEqual ((int?) 0, c (1, 0), "a2");
Assert.AreEqual ((int?) 0, c (0, 1), "a3");
Assert.AreEqual ((int?) 0, c (0, 0), "a4");
Assert.AreEqual ((int?) null, c (1, null), "a5");
Assert.AreEqual ((int?) null, c (0, null), "a6");
Assert.AreEqual ((int?) null, c (null, 0), "a7");
Assert.AreEqual ((int?) null, c (1, null), "a8");
Assert.AreEqual ((int?) null, c (null, null), "a9");
}
}
}

View File

@@ -0,0 +1,386 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
// Jb Evain <jbevain@novell.com>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_AndAlso
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.AndAlso (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.AndAlso (Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void NoOperatorClass ()
{
Expression.AndAlso (Expression.Constant (new NoOpClass ()), Expression.Constant (new NoOpClass ()));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void Double ()
{
Expression.AndAlso (Expression.Constant (1.0), Expression.Constant (2.0));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void Integer ()
{
Expression.AndAlso (Expression.Constant (1), Expression.Constant (2));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void MismatchedTypes ()
{
Expression.AndAlso (Expression.Constant (new OpClass ()), Expression.Constant (true));
}
[Test]
public void Boolean ()
{
BinaryExpression expr = Expression.AndAlso (Expression.Constant (true), Expression.Constant (false));
Assert.AreEqual (ExpressionType.AndAlso, expr.NodeType, "AndAlso#01");
Assert.AreEqual (typeof (bool), expr.Type, "AndAlso#02");
Assert.IsNull (expr.Method, "AndAlso#03");
#if !NET_4_0
Assert.AreEqual ("(True && False)", expr.ToString(), "AndAlso#04");
#endif
}
[Test]
public void UserDefinedClass ()
{
// We can use the simplest version of GetMethod because we already know only one
// exists in the very simple class we're using for the tests.
MethodInfo mi = typeof (OpClass).GetMethod ("op_BitwiseAnd");
BinaryExpression expr = Expression.AndAlso (Expression.Constant (new OpClass ()), Expression.Constant (new OpClass ()));
Assert.AreEqual (ExpressionType.AndAlso, expr.NodeType, "AndAlso#05");
Assert.AreEqual (typeof (OpClass), expr.Type, "AndAlso#06");
Assert.AreEqual (mi, expr.Method, "AndAlso#07");
Assert.AreEqual ("op_BitwiseAnd", expr.Method.Name, "AndAlso#08");
#if !NET_4_0
Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) && value(MonoTests.System.Linq.Expressions.OpClass))",
expr.ToString(), "AndAlso#09");
#endif
}
[Test]
public void AndAlsoTest ()
{
var a = Expression.Parameter (typeof (bool), "a");
var b = Expression.Parameter (typeof (bool), "b");
var l = Expression.Lambda<Func<bool, bool, bool>> (
Expression.AndAlso (a, b), a, b);
var be = l.Body as BinaryExpression;
Assert.IsNotNull (be);
Assert.AreEqual (typeof (bool), be.Type);
Assert.IsFalse (be.IsLifted);
Assert.IsFalse (be.IsLiftedToNull);
var c = l.Compile ();
Assert.AreEqual (true, c (true, true), "a1");
Assert.AreEqual (false, c (true, false), "a2");
Assert.AreEqual (false, c (false, true), "a3");
Assert.AreEqual (false, c (false, false), "a4");
}
[Test]
public void AndAlsoLifted ()
{
var b = Expression.AndAlso (
Expression.Constant (null, typeof (bool?)),
Expression.Constant (null, typeof (bool?)));
Assert.AreEqual (typeof (bool?), b.Type);
Assert.IsTrue (b.IsLifted);
Assert.IsTrue (b.IsLiftedToNull);
}
[Test]
public void AndAlsoNotLifted ()
{
var b = Expression.AndAlso (
Expression.Constant (true, typeof (bool)),
Expression.Constant (true, typeof (bool)));
Assert.AreEqual (typeof (bool), b.Type);
Assert.IsFalse (b.IsLifted);
Assert.IsFalse (b.IsLiftedToNull);
}
[Test]
[Category ("NotWorkingInterpreter")]
public void AndAlsoTestNullable ()
{
var a = Expression.Parameter (typeof (bool?), "a");
var b = Expression.Parameter (typeof (bool?), "b");
var l = Expression.Lambda<Func<bool?, bool?, bool?>> (
Expression.AndAlso (a, b), a, b);
var be = l.Body as BinaryExpression;
Assert.IsNotNull (be);
Assert.AreEqual (typeof (bool?), be.Type);
Assert.IsTrue (be.IsLifted);
Assert.IsTrue (be.IsLiftedToNull);
var c = l.Compile ();
Assert.AreEqual (true, c (true, true), "a1");
Assert.AreEqual (false, c (true, false), "a2");
Assert.AreEqual (false, c (false, true), "a3");
Assert.AreEqual (false, c (false, false), "a4");
Assert.AreEqual (null, c (true, null), "a5");
Assert.AreEqual (false, c (false, null), "a6");
Assert.AreEqual (false, c (null, false), "a7");
Assert.AreEqual (null, c (true, null), "a8");
Assert.AreEqual (null, c (null, null), "a9");
}
[Test]
public void AndAlsoBoolItem ()
{
var i = Expression.Parameter (typeof (Item<bool>), "i");
var and = Expression.Lambda<Func<Item<bool>, bool>> (
Expression.AndAlso (
Expression.Property (i, "Left"),
Expression.Property (i, "Right")), i).Compile ();
var item = new Item<bool> (false, true);
Assert.AreEqual (false, and (item));
Assert.IsTrue (item.LeftCalled);
Assert.IsFalse (item.RightCalled);
}
[Test]
[Category ("NotWorkingInterpreter")]
public void AndAlsoNullableBoolItem ()
{
var i = Expression.Parameter (typeof (Item<bool?>), "i");
var and = Expression.Lambda<Func<Item<bool?>, bool?>> (
Expression.AndAlso (
Expression.Property (i, "Left"),
Expression.Property (i, "Right")), i).Compile ();
var item = new Item<bool?> (false, true);
Assert.AreEqual ((bool?) false, and (item));
Assert.IsTrue (item.LeftCalled);
Assert.IsFalse (item.RightCalled);
}
struct Slot {
public int Value;
public Slot (int val)
{
this.Value = val;
}
public static Slot operator & (Slot a, Slot b)
{
return new Slot (a.Value & b.Value);
}
public static bool operator true (Slot a)
{
return a.Value != 0;
}
public static bool operator false (Slot a)
{
return a.Value == 0;
}
public override string ToString ()
{
return Value.ToString ();
}
}
[Test]
[Category ("NotWorkingInterpreter")]
public void UserDefinedAndAlso ()
{
var l = Expression.Parameter (typeof (Slot), "l");
var r = Expression.Parameter (typeof (Slot), "r");
var method = typeof (Slot).GetMethod ("op_BitwiseAnd");
var node = Expression.AndAlso (l, r, method);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
Assert.AreEqual (method, node.Method);
var andalso = Expression.Lambda<Func<Slot, Slot, Slot>> (node, l, r).Compile ();
Assert.AreEqual (new Slot (64), andalso (new Slot (64), new Slot (64)));
Assert.AreEqual (new Slot (0), andalso (new Slot (32), new Slot (64)));
Assert.AreEqual (new Slot (0), andalso (new Slot (64), new Slot (32)));
}
[Test]
[Category ("NotWorkingInterpreter")]
public void UserDefinedAndAlsoShortCircuit ()
{
var i = Expression.Parameter (typeof (Item<Slot>), "i");
var and = Expression.Lambda<Func<Item<Slot>, Slot>> (
Expression.AndAlso (
Expression.Property (i, "Left"),
Expression.Property (i, "Right")), i).Compile ();
var item = new Item<Slot> (new Slot (0), new Slot (1));
Assert.AreEqual (new Slot (0), and (item));
Assert.IsTrue (item.LeftCalled);
Assert.IsFalse (item.RightCalled);
}
[Test]
[Category ("NotWorkingInterpreter")]
[Category ("NotDotNet")] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=350228
public void UserDefinedLiftedAndAlsoShortCircuit ()
{
var i = Expression.Parameter (typeof (Item<Slot?>), "i");
var and = Expression.Lambda<Func<Item<Slot?>, Slot?>> (
Expression.AndAlso (
Expression.Property (i, "Left"),
Expression.Property (i, "Right")), i).Compile ();
var item = new Item<Slot?> (null, new Slot (1));
Assert.AreEqual ((Slot?) null, and (item));
Assert.IsTrue (item.LeftCalled);
Assert.IsFalse (item.RightCalled);
}
[Test]
[Category ("NotWorkingInterpreter")]
public void UserDefinedAndAlsoLiftedToNull ()
{
var l = Expression.Parameter (typeof (Slot?), "l");
var r = Expression.Parameter (typeof (Slot?), "r");
var method = typeof (Slot).GetMethod ("op_BitwiseAnd");
var node = Expression.AndAlso (l, r, method);
Assert.IsTrue (node.IsLifted);
Assert.IsTrue (node.IsLiftedToNull);
Assert.AreEqual (method, node.Method);
var andalso = Expression.Lambda<Func<Slot?, Slot?, Slot?>> (node, l, r).Compile ();
Assert.AreEqual (new Slot (64), andalso (new Slot (64), new Slot (64)));
Assert.AreEqual (new Slot (0), andalso (new Slot (32), new Slot (64)));
Assert.AreEqual (new Slot (0), andalso (new Slot (64), new Slot (32)));
Assert.AreEqual (null, andalso (null, new Slot (32)));
Assert.AreEqual (null, andalso (new Slot (64), null));
Assert.AreEqual (null, andalso (null, null));
}
struct Incomplete {
public int Value;
public Incomplete (int val)
{
Value = val;
}
public static Incomplete operator & (Incomplete a, Incomplete b)
{
return new Incomplete (a.Value & b.Value);
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void IncompleteUserDefinedAndAlso ()
{
var l = Expression.Parameter (typeof (Incomplete), "l");
var r = Expression.Parameter (typeof (Incomplete), "r");
var method = typeof (Incomplete).GetMethod ("op_BitwiseAnd");
Expression.AndAlso (l, r, method);
}
class A {
public static bool operator true (A x)
{
return true;
}
public static bool operator false (A x)
{
return false;
}
}
class B : A {
public static B operator & (B x, B y)
{
return new B ();
}
public static bool op_True<T> (B x)
{
return true;
}
public static bool op_False (B x)
{
return false;
}
}
[Test] // from https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=350487
[Category ("NotWorkingInterpreter")]
public void Connect350487 ()
{
var p = Expression.Parameter (typeof (B), "b");
var l = Expression.Lambda<Func<B, A>> (
Expression.AndAlso (p, p), p).Compile ();
Assert.IsNotNull (l (null));
}
}
}

View File

@@ -0,0 +1,211 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_ArrayIndex
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.ArrayIndex (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null1 ()
{
Expression.ArrayIndex (Expression.Constant (new int[1]), (Expression)null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null2 ()
{
Expression.ArrayIndex (Expression.Constant (new int[1]), (IEnumerable<Expression>)null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null3 ()
{
Expression.ArrayIndex (Expression.Constant (new int[1]), (Expression[])null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Arg2WrongType1 ()
{
Expression.ArrayIndex (Expression.Constant (new int[1]), Expression.Constant (true));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Arg1NotArray ()
{
Expression.ArrayIndex (Expression.Constant ("This is not an array!"), Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Arg2WrongType2 ()
{
Expression[] indexes = { Expression.Constant (1), Expression.Constant (1L) };
Expression.ArrayIndex (Expression.Constant (new int[1,1]), indexes);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Arg2WrongNumber1 ()
{
Expression[] indexes = { Expression.Constant (1), Expression.Constant (0) };
Expression.ArrayIndex (Expression.Constant (new int[1]), indexes);
}
[Test]
public void Rank1Struct ()
{
int[] array = { 42 };
BinaryExpression expr = Expression.ArrayIndex (Expression.Constant (array), Expression.Constant(0));
Assert.AreEqual (ExpressionType.ArrayIndex, expr.NodeType, "ArrayIndex#01");
Assert.AreEqual (typeof (int), expr.Type, "ArrayIndex#02");
Assert.IsNull (expr.Method, "ArrayIndex#03");
Assert.AreEqual ("value(System.Int32[])[0]", expr.ToString(), "ArrayIndex#04");
}
[Test]
public void Rank1UserDefinedClass ()
{
NoOpClass[] array = { new NoOpClass() };
BinaryExpression expr = Expression.ArrayIndex (Expression.Constant (array), Expression.Constant(0));
Assert.AreEqual (ExpressionType.ArrayIndex, expr.NodeType, "ArrayIndex#05");
Assert.AreEqual (typeof (NoOpClass), expr.Type, "ArrayIndex#06");
Assert.IsNull (expr.Method, "ArrayIndex#07");
Assert.AreEqual ("value(MonoTests.System.Linq.Expressions.NoOpClass[])[0]", expr.ToString(), "ArrayIndex#08");
}
[Test]
public void Rank2Struct ()
{
int[,] array = { {42}, {42} };
Expression[] indexes = { Expression.Constant (1), Expression.Constant (0) };
MethodCallExpression expr = Expression.ArrayIndex (Expression.Constant (array), indexes);
Assert.AreEqual (ExpressionType.Call, expr.NodeType, "ArrayIndex#09");
Assert.AreEqual (typeof (int), expr.Type, "ArrayIndex#10");
Assert.AreEqual ("value(System.Int32[,]).Get(1, 0)", expr.ToString(), "ArrayIndex#12");
}
[Test]
public void Rank2UserDefinedClass ()
{
NoOpClass[,] array = { {new NoOpClass()}, {new NoOpClass()} };
Expression[] indexes = { Expression.Constant (1), Expression.Constant (0) };
MethodCallExpression expr = Expression.ArrayIndex (Expression.Constant (array), indexes);
Assert.AreEqual (ExpressionType.Call, expr.NodeType, "ArrayIndex#13");
Assert.AreEqual (typeof (NoOpClass), expr.Type, "ArrayIndex#14");
Assert.AreEqual ("value(MonoTests.System.Linq.Expressions.NoOpClass[,]).Get(1, 0)", expr.ToString(), "ArrayIndex#16");
}
static Func<T [], int, T> CreateArrayAccess<T> ()
{
var a = Expression.Parameter (typeof (T []), "a");
var i = Expression.Parameter (typeof (int), "i");
return Expression.Lambda<Func<T [], int, T>> (
Expression.ArrayIndex (a, i), a, i).Compile ();
}
[Test]
public void CompileIntArrayAccess ()
{
var array = new int [] { 1, 2, 3, 4 };
var at = CreateArrayAccess<int> ();
Assert.AreEqual (1, at (array, 0));
Assert.AreEqual (4, at (array, 3));
}
[Test]
public void CompileShortArrayAccess ()
{
var array = new short [] { 1, 2, 3, 4 };
var at = CreateArrayAccess<short> ();
Assert.AreEqual (array [0], at (array, 0));
Assert.AreEqual (array [3], at (array, 3));
}
enum Months { Jan, Feb, Mar, Apr };
[Test]
public void CompileEnumArrayAccess ()
{
var array = new Months [] { Months.Jan, Months.Feb, Months.Mar, Months.Apr };
var at = CreateArrayAccess<Months> ();
Assert.AreEqual (array [0], at (array, 0));
Assert.AreEqual (array [3], at (array, 3));
}
class Foo {
}
[Test]
public void CompileClassArrayAccess ()
{
var array = new Foo [] { new Foo (), new Foo (), new Foo (), new Foo () };
var at = CreateArrayAccess<Foo> ();
Assert.AreEqual (array [0], at (array, 0));
Assert.AreEqual (array [3], at (array, 3));
}
struct Bar {
public int bar;
public Bar (int b) { bar = b; }
}
[Test]
public void CompileStructArrayAccess ()
{
var array = new Bar [] { new Bar (0), new Bar (1), new Bar (2), new Bar (3) };
var at = CreateArrayAccess<Bar> ();
Assert.AreEqual (array [0], at (array, 0));
Assert.AreEqual (array [3], at (array, 3));
}
}
}

View File

@@ -0,0 +1,88 @@
//
// ExpressionTest_ArrayLength.cs
//
// Author:
// Federico Di Gregorio <fog@initd.org>
// Jb Evain (jbevain@novell.com)
//
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_ArrayLength
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.ArrayLength (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Arg1NotArray ()
{
Expression.ArrayLength (Expression.Constant ("This is not an array!"));
}
[Test]
public void Rank1String ()
{
string[] array = { "a", "b", "c" };
UnaryExpression expr = Expression.ArrayLength (Expression.Constant (array));
Assert.AreEqual (ExpressionType.ArrayLength, expr.NodeType, "ArrayLength#01");
Assert.AreEqual (typeof (int), expr.Type, "ArrayLength#02");
Assert.IsNull (expr.Method, "ArrayLength#03");
Assert.AreEqual ("ArrayLength(value(System.String[]))", expr.ToString(), "ArrayLength#04");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Rank2String ()
{
string[,] array = {{ }, { }};
Expression.ArrayLength (Expression.Constant (array));
}
[Test]
public void CompileArrayLength ()
{
var p = Expression.Parameter (typeof (object []), "ary");
var len = Expression.Lambda<Func<object [], int>> (
Expression.ArrayLength (p), p).Compile ();
Assert.AreEqual (0, len (new string [0]));
Assert.AreEqual (2, len (new [] { "jb", "evain" }));
}
}
}

View File

@@ -0,0 +1,163 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Bind
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Bind (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.Bind (MemberClass.GetRwFieldInfo (), null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Method1 ()
{
// This tests the MethodInfo version of Bind(): should raise an exception
// because the method is not an accessor.
Expression.Bind (MemberClass.GetMethodInfo (), Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Method2 ()
{
// This tests the MemberInfo version of Bind(): should raise an exception
// because the argument is not a field or property accessor.
Expression.Bind ((MemberInfo)MemberClass.GetMethodInfo (), Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Event ()
{
Expression.Bind (MemberClass.GetEventInfo (), Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void PropertyRo ()
{
Expression.Bind (MemberClass.GetRoPropertyInfo (), Expression.Constant (1));
}
[Test]
public void FieldRo ()
{
MemberAssignment expr = Expression.Bind (MemberClass.GetRoFieldInfo (), Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#01");
Assert.AreEqual ("TestField1 = 1", expr.ToString(), "Bind#02");
}
[Test]
public void FieldRw ()
{
MemberAssignment expr = Expression.Bind (MemberClass.GetRwFieldInfo (), Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#03");
Assert.AreEqual ("TestField2 = 1", expr.ToString(), "Bind#04");
}
[Test]
public void FieldStatic ()
{
MemberAssignment expr = Expression.Bind (MemberClass.GetStaticFieldInfo (), Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#05");
Assert.AreEqual ("StaticField = 1", expr.ToString(), "Bind#06");
}
[Test]
public void PropertyRw ()
{
MemberAssignment expr = Expression.Bind (MemberClass.GetRwPropertyInfo (), Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#07");
Assert.AreEqual ("TestProperty2 = 1", expr.ToString(), "Bind#08");
}
[Test]
public void PropertyStatic ()
{
MemberAssignment expr = Expression.Bind (MemberClass.GetStaticPropertyInfo (), Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#09");
Assert.AreEqual ("StaticProperty = 1", expr.ToString(), "Bind#10");
}
[Test]
public void PropertyAccessor ()
{
MethodInfo mi = typeof(MemberClass).GetMethod("get_TestProperty2");
MemberAssignment expr = Expression.Bind (mi, Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#11");
Assert.AreEqual ("TestProperty2 = 1", expr.ToString(), "Bind#12");
Assert.AreEqual (MemberClass.GetRwPropertyInfo(), expr.Member, "Bind#13");
}
[Test]
public void PropertyAccessorStatic ()
{
MethodInfo mi = typeof(MemberClass).GetMethod("get_StaticProperty");
MemberAssignment expr = Expression.Bind (mi, Expression.Constant (1));
Assert.AreEqual (MemberBindingType.Assignment, expr.BindingType, "Bind#14");
Assert.AreEqual ("StaticProperty = 1", expr.ToString(), "Bind#15");
Assert.AreEqual (MemberClass.GetStaticPropertyInfo(), expr.Member, "Bind#16");
}
struct Slot {
public int Integer { get; set; }
public short Short { get; set; }
}
[Test]
[Category ("NotWorkingInterpreter")]
public void BindValueTypes ()
{
var i = Expression.Parameter (typeof (int), "i");
var s = Expression.Parameter (typeof (short), "s");
var gslot = Expression.Lambda<Func<int, short, Slot>> (
Expression.MemberInit (
Expression.New (typeof (Slot)),
Expression.Bind (typeof (Slot).GetProperty ("Integer"), i),
Expression.Bind (typeof (Slot).GetProperty ("Short"), s)), i, s).Compile ();
Assert.AreEqual (new Slot { Integer = 42, Short = -1 }, gslot (42, -1));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,246 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
// Jb Evain <jbevain@novell.com>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Coalesce
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Coalesce (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.Coalesce (Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void NonNullLeftParameter ()
{
// This throws because they are both doubles, which are never
Expression.Coalesce (Expression.Constant (1.0), Expression.Constant (2.0));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Incompatible_Arguments ()
{
// The artuments are not compatible
Expression.Coalesce (Expression.Parameter (typeof (int?), "a"),
Expression.Parameter (typeof (bool), "b"));
}
[Test]
public void IsCoalesceStringLifted ()
{
var coalesce = Expression.Coalesce (
Expression.Parameter (typeof (string), "a"),
Expression.Parameter (typeof (string), "b"));
Assert.AreEqual ("(a ?? b)", coalesce.ToString ());
Assert.IsFalse (coalesce.IsLifted);
Assert.IsFalse (coalesce.IsLiftedToNull);
}
[Test]
public void IsCoalesceNullableIntLifted ()
{
var coalesce = Expression.Coalesce (
Expression.Parameter (typeof (int?), "a"),
Expression.Parameter (typeof (int?), "b"));
Assert.IsFalse (coalesce.IsLifted);
Assert.IsFalse (coalesce.IsLiftedToNull);
}
[Test]
[Category ("NotWorkingInterpreter")]
public void CoalesceNullableInt ()
{
var a = Expression.Parameter (typeof (int?), "a");
var b = Expression.Parameter (typeof (int?), "b");
var coalesce = Expression.Lambda<Func<int?, int?, int?>> (
Expression.Coalesce (a, b), a, b).Compile ();
Assert.AreEqual ((int?) 1, coalesce (1, 2));
Assert.AreEqual ((int?) null, coalesce (null, null));
Assert.AreEqual ((int?) 2, coalesce (null, 2));
Assert.AreEqual ((int?) 2, coalesce (2, null));
}
[Test]
public void CoalesceString ()
{
var a = Expression.Parameter (typeof (string), "a");
var b = Expression.Parameter (typeof (string), "b");
var coalesce = Expression.Lambda<Func<string, string, string>> (
Expression.Coalesce (a, b), a, b).Compile ();
Assert.AreEqual ("foo", coalesce ("foo", "bar"));
Assert.AreEqual (null, coalesce (null, null));
Assert.AreEqual ("bar", coalesce (null, "bar"));
Assert.AreEqual ("foo", coalesce ("foo", null));
}
[Test]
[Category ("NotWorkingInterpreter")]
public void CoalesceNullableToNonNullable ()
{
var a = Expression.Parameter (typeof (int?), "a");
var node = Expression.Coalesce (a, Expression.Constant (99, typeof (int)));
Assert.AreEqual (typeof (int), node.Type);
Assert.IsFalse (node.IsLifted);
Assert.IsFalse (node.IsLiftedToNull);
var coalesce = Expression.Lambda<Func<int?, int>> (node, a).Compile ();
Assert.AreEqual (5, coalesce (5));
Assert.AreEqual (99, coalesce (null));
}
[Test]
[Category ("NotWorkingInterpreter")]
[Category ("NotDotNet")] // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=349822
public void CoalesceUserDefinedConversion ()
{
var s = Expression.Parameter (typeof (string), "s");
var coalesce = Expression.Lambda<Func<string, int>> (
Expression.Coalesce (
s,
Expression.Constant (42),
Expression.Lambda<Func<string, int>> (
Expression.Call (typeof (int).GetMethod ("Parse", new [] { typeof (string) }), s), s)), s).Compile ();
Assert.AreEqual (12, coalesce ("12"));
Assert.AreEqual (42, coalesce (null));
}
struct Slot {
int Value;
public Slot (int v)
{
Value = v;
}
public static implicit operator int (Slot s)
{
return s.Value;
}
}
[Test]
// #12987
[Category ("MobileNotWorking")]
[Category ("NotWorkingInterpreter")]
public void CoalesceNullableSlotIntoInteger ()
{
var s = Expression.Parameter (typeof (Slot?), "s");
var method = typeof (Slot).GetMethod ("op_Implicit");
var coalesce = Expression.Lambda<Func<Slot?, int>> (
Expression.Coalesce (
s,
Expression.Constant (-3),
Expression.Lambda (
Expression.Convert (s, typeof (int), method),
s)), s).Compile ();
Assert.AreEqual (-3, coalesce (null));
Assert.AreEqual (42, coalesce (new Slot (42)));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void WrongCoalesceConversionParameterCount ()
{
var s = Expression.Parameter (typeof (string), "s");
var p = Expression.Parameter (typeof (string), "foo");
Expression.Coalesce (
s,
42.ToConstant (),
Expression.Lambda<Func<string, string, int>> (
Expression.Call (typeof (int).GetMethod ("Parse", new [] { typeof (string) }), s), s, p));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void WrongCoalesceConversionParameterType ()
{
var s = Expression.Parameter (typeof (string), "s");
var i = Expression.Parameter (typeof (int), "i");
Expression.Coalesce (
s,
42.ToConstant (),
Expression.Lambda<Func<int, int>> (
i, i));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void WrongCoalesceConversionReturnType ()
{
var s = Expression.Parameter (typeof (string), "s");
Expression.Coalesce (
s,
42.ToConstant (),
Expression.Lambda<Func<string, string>> (
s, s));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CoalesceVoidUserDefinedConversion ()
{
var s = Expression.Parameter (typeof (string), "s");
Expression.Coalesce (
s,
42.ToConstant (),
Expression.Lambda<Action<string>> (
Expression.Call (typeof (int).GetMethod ("Parse", new [] { typeof (string) }), s), s));
}
}
}

View File

@@ -0,0 +1,105 @@
//
// ExpressionTest.cs
//
// Author:
// Jb Evain (jbevain@novell.com)
//
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions {
[TestFixture]
public class ExpressionTest_Condition {
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Condition (null, Expression.Constant (1), Expression.Constant (0));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.Condition (Expression.Equal (Expression.Constant (42), Expression.Constant (42)), null, Expression.Constant (0));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg3Null ()
{
Expression.Condition (Expression.Equal (Expression.Constant (42), Expression.Constant (42)), Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestNotBool ()
{
Expression.Condition (Expression.Constant (42), Expression.Constant (1), Expression.Constant (0));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TrueBlockTypeNotFalseBlockType ()
{
Expression.Condition (Expression.Constant (42), Expression.Constant (1.1), Expression.Constant (0));
}
[Test]
public void TestSimpleConditional ()
{
var cond = Expression.Condition (Expression.GreaterThan (Expression.Constant (2), Expression.Constant (1)), Expression.Constant (1), Expression.Constant (0));
Assert.AreEqual (typeof (bool), cond.Test.Type);
Assert.AreEqual ("IIF((2 > 1), 1, 0)", cond.ToString ());
}
[Test]
public void CompileConditional ()
{
var parameters = new [] { Expression.Parameter (typeof (int), "number") };
var l = Expression.Lambda<Func<int, string>> (
Expression.Condition (
Expression.GreaterThanOrEqual (
parameters [0],
Expression.Constant (0)),
Expression.Constant ("+"),
Expression.Constant ("-")),
parameters);
var gt = l.Compile ();
Assert.AreEqual ("+", gt (1));
Assert.AreEqual ("+", gt (0));
Assert.AreEqual ("-", gt (-1));
}
}
}

View File

@@ -0,0 +1,288 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Constant
{
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Arg2NotNullable ()
{
Expression.Constant(null, typeof(int));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.Constant (1, null);
}
[Test]
public void NullValue ()
{
ConstantExpression expr = Expression.Constant (null);
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#01");
Assert.IsNull (expr.Value, "Constant#02");
Assert.AreEqual (typeof (object), expr.Type, "Constant#03");
Assert.AreEqual ("null", expr.ToString(), "Constant#04");
}
[Test]
public void NullableValue1 ()
{
ConstantExpression expr = Expression.Constant (null, typeof(int?));
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#05");
Assert.IsNull (expr.Value, "Constant#06");
Assert.AreEqual (typeof (int?), expr.Type, "Constant#07");
Assert.AreEqual ("null", expr.ToString(), "Constant#08");
}
[Test]
public void NullableValue2 ()
{
ConstantExpression expr = Expression.Constant (1, typeof (int?));
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#09");
Assert.AreEqual (1, expr.Value, "Constant#10");
Assert.AreEqual (typeof (int?), expr.Type, "Constant#11");
Assert.AreEqual ("1", expr.ToString(), "Constant#12");
}
[Test]
public void NullableValue3 ()
{
ConstantExpression expr = Expression.Constant ((int?)1);
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#13");
Assert.AreEqual (1, expr.Value, "Constant#14");
Assert.AreEqual (typeof (int), expr.Type, "Constant#15");
Assert.AreEqual ("1", expr.ToString(), "Constant#16");
}
[Test]
public void IntegerValue ()
{
ConstantExpression expr = Expression.Constant (0);
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#17");
Assert.AreEqual (0, expr.Value, "Constant#18");
Assert.AreEqual (typeof (int), expr.Type, "Constant#19");
Assert.AreEqual ("0", expr.ToString(), "Constant#20");
}
[Test]
public void StringValue ()
{
ConstantExpression expr = Expression.Constant ("a string");
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#21");
Assert.AreEqual ("a string", expr.Value, "Constant#22");
Assert.AreEqual (typeof (string), expr.Type, "Constant#23");
Assert.AreEqual ("\"a string\"", expr.ToString(), "Constant#24");
}
[Test]
public void DateTimeValue ()
{
ConstantExpression expr = Expression.Constant (new DateTime(1971, 10, 19));
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#25");
Assert.AreEqual (new DateTime(1971, 10, 19), expr.Value, "Constant#26");
Assert.AreEqual (typeof (DateTime), expr.Type, "Constant#27");
Assert.AreEqual (new DateTime(1971, 10, 19).ToString(), expr.ToString(), "Constant#28");
}
[Test]
public void UserClassValue ()
{
OpClass oc = new OpClass ();
ConstantExpression expr = Expression.Constant (oc);
Assert.AreEqual (ExpressionType.Constant, expr.NodeType, "Constant#29");
Assert.AreEqual (oc, expr.Value, "Constant#30");
Assert.AreEqual (typeof (OpClass), expr.Type, "Constant#31");
Assert.AreEqual ("value(MonoTests.System.Linq.Expressions.OpClass)", expr.ToString(), "Constant#32");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestInvalidCtor_1 ()
{
// null value, type == valuetype is invalid
Expression.Constant (null, typeof (int));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestInvalidCtor_2 ()
{
// type mismatch: int value, type == double
Expression.Constant (0, typeof (double));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void VoidConstant ()
{
Expression.Constant (null, typeof (void));
}
static T Check<T> (T val)
{
Expression<Func<T>> l = Expression.Lambda<Func<T>> (Expression.Constant (val), new ParameterExpression [0]);
Func<T> fi = l.Compile ();
return fi ();
}
[Test]
public void NullableConstant_ToConstant ()
{
int? a = 1;
ConstantExpression c = Expression.Constant (a);
Assert.AreEqual (typeof (int), c.Type, "#1");
Assert.AreEqual (1, c.Value, "#2");
}
[Test]
public void ConstantCodeGen ()
{
Assert.AreEqual (Check<int> (0), 0, "int");
Assert.AreEqual (Check<int> (128), 128, "int2");
Assert.AreEqual (Check<int> (-128), -128, "int3");
Assert.AreEqual (Check<int> (Int32.MinValue), Int32.MinValue, "int4");
Assert.AreEqual (Check<int> (Int32.MaxValue), Int32.MaxValue, "int5");
Assert.AreEqual (Check<uint> (128), 128, "uint");
Assert.AreEqual (Check<uint> (0), 0, "uint2");
Assert.AreEqual (Check<uint> (UInt32.MinValue), UInt32.MinValue, "uint3");
Assert.AreEqual (Check<uint> (UInt32.MaxValue), UInt32.MaxValue, "uint4");
Assert.AreEqual (Check<byte> (10), 10, "byte");
Assert.AreEqual (Check<byte> (Byte.MinValue), Byte.MinValue, "byte2");
Assert.AreEqual (Check<byte> (Byte.MaxValue), Byte.MaxValue, "byte3");
Assert.AreEqual (Check<short> (128), 128, "short");
Assert.AreEqual (Check<short> (-128), -128, "short");
Assert.AreEqual (Check<short> (Int16.MinValue), Int16.MinValue, "short2");
Assert.AreEqual (Check<short> (Int16.MaxValue), Int16.MaxValue, "short3");
Assert.AreEqual (Check<ushort> (128), 128, "ushort");
Assert.AreEqual (Check<ushort> (UInt16.MinValue), UInt16.MinValue, "short2");
Assert.AreEqual (Check<ushort> (UInt16.MaxValue), UInt16.MaxValue, "short3");
Assert.AreEqual (Check<bool> (true), true, "bool1");
Assert.AreEqual (Check<bool> (false), false, "bool2");
Assert.AreEqual (Check<long> (Int64.MaxValue), Int64.MaxValue, "long");
Assert.AreEqual (Check<long> (Int64.MinValue), Int64.MinValue, "long2");
Assert.AreEqual (Check<ulong> (UInt64.MaxValue), UInt64.MaxValue, "ulong");
Assert.AreEqual (Check<ulong> (UInt64.MinValue), UInt64.MinValue, "ulong2");
Assert.AreEqual (Check<ushort> (200), 200, "ushort");
Assert.AreEqual (Check<float> (2.0f), 2.0f, "float");
Assert.AreEqual (Check<double> (2.312), 2.312, "double");
Assert.AreEqual (Check<string> ("dingus"), "dingus", "string");
Assert.AreEqual (Check<decimal> (1.3m), 1.3m, "");
// this forces the other code path for decimal.
Assert.AreEqual (Check<decimal> (3147483647m), 3147483647m, "decimal");
}
delegate void Foo ();
[Test]
public void DelegateTypeConstant ()
{
Expression.Constant (typeof (Foo), typeof (Type));
}
[Test]
public void EmitDateTimeConstant ()
{
var date = new DateTime (1983, 2, 6);
var lambda = Expression.Lambda<Func<DateTime>> (Expression.Constant (date)).Compile ();
Assert.AreEqual (date, lambda ());
}
[Test]
public void EmitDBNullConstant ()
{
var lambda = Expression.Lambda<Func<DBNull>> (Expression.Constant (DBNull.Value)).Compile ();
Assert.AreEqual (DBNull.Value, lambda ());
}
[Test]
public void EmitNullString ()
{
var n = Expression.Lambda<Func<string>> (
Expression.Constant (null, typeof (string))).Compile ();
Assert.IsNull (n ());
}
[Test]
public void EmitNullNullableType ()
{
var n = Expression.Lambda<Func<int?>> (
Expression.Constant (null, typeof (int?))).Compile ();
Assert.IsNull (n ());
}
[Test]
public void EmitNullableInt ()
{
var i = Expression.Lambda<Func<int?>> (
Expression.Constant ((int?) 42, typeof (int?))).Compile ();
Assert.AreEqual ((int?) 42, i ());
}
[Test]
public void EmitNullableEnum ()
{
var e = Expression.Lambda<Func<Chose?>> (
Expression.Constant ((Chose?) Chose.Moche, typeof (Chose?))).Compile ();
Assert.AreEqual ((Chose?) Chose.Moche, e ());
}
enum Chose { Moche }
interface IBar {}
class Bar : IBar {}
interface IBaz<T> {}
class Baz<T> : IBaz<T> {}
[Test]
public void ConstantInterface ()
{
var c = Expression.Constant (new Bar (), typeof (IBar));
Assert.AreEqual (typeof (IBar), c.Type);
}
[Test]
public void ConstantGenericInterface ()
{
var c = Expression.Constant (new Baz<string> (), typeof (IBaz<string>));
Assert.AreEqual (typeof (IBaz<string>), c.Type);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Divide
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Divide (null, Expression.Constant (1));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg2Null ()
{
Expression.Divide (Expression.Constant (1), null);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void ArgTypesDifferent ()
{
Expression.Divide (Expression.Constant (1), Expression.Constant (2.0));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void NoOperatorClass ()
{
Expression.Divide (Expression.Constant (new NoOpClass ()), Expression.Constant (new NoOpClass ()));
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void Boolean ()
{
Expression.Divide (Expression.Constant (true), Expression.Constant (false));
}
[Test]
public void Numeric ()
{
BinaryExpression expr = Expression.Divide (Expression.Constant (1), Expression.Constant (2));
Assert.AreEqual (ExpressionType.Divide, expr.NodeType, "Divide#01");
Assert.AreEqual (typeof (int), expr.Type, "Divide#02");
Assert.IsNull (expr.Method, "Divide#03");
Assert.AreEqual ("(1 / 2)", expr.ToString(), "Divide#04");
}
[Test]
public void Nullable ()
{
int? a = 1;
int? b = 2;
BinaryExpression expr = Expression.Divide (Expression.Constant (a), Expression.Constant (b));
Assert.AreEqual (ExpressionType.Divide, expr.NodeType, "Divide#05");
Assert.AreEqual (typeof (int), expr.Type, "Divide#06");
Assert.IsNull (expr.Method, "Divide#07");
Assert.AreEqual ("(1 / 2)", expr.ToString(), "Divide#08");
}
[Test]
public void UserDefinedClass ()
{
// We can use the simplest version of GetMethod because we already know only one
// exists in the very simple class we're using for the tests.
MethodInfo mi = typeof (OpClass).GetMethod ("op_Division");
BinaryExpression expr = Expression.Divide (Expression.Constant (new OpClass ()), Expression.Constant (new OpClass ()));
Assert.AreEqual (ExpressionType.Divide, expr.NodeType, "Divide#09");
Assert.AreEqual (typeof (OpClass), expr.Type, "Divide#10");
Assert.AreEqual (mi, expr.Method, "Divide#11");
Assert.AreEqual ("op_Division", expr.Method.Name, "Divide#12");
Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) / value(MonoTests.System.Linq.Expressions.OpClass))",
expr.ToString(), "Divide#13");
}
}
}

Some files were not shown because too many files have changed in this diff Show More