How to use Dummy class of B package

Best Nunit code snippet using B.Dummy

ValidatorTest.cs

Source:ValidatorTest.cs Github

copy

Full Screen

...37	{38		[Test]39		public void TryValidateObject_Object_ValidationContext_ICollection_01 ()40		{41			var dummy = new DummyNoAttributes ();42			var ctx = new ValidationContext (dummy, null, null);43			var results = new List<ValidationResult> ();44			AssertExtensions.Throws<ArgumentNullException> (() => {45				Validator.TryValidateObject (null, ctx, results);46			}, "#A1-1");47			AssertExtensions.Throws<ArgumentNullException> (() => {48				Validator.TryValidateObject (dummy, null, results);49			}, "#A1-2");50			bool valid = Validator.TryValidateObject (dummy, ctx, null);51			Assert.IsTrue (valid, "#A2-1");52			Assert.IsTrue (results.Count == 0, "#A2-2");53		}54		[Test]55		public void TryValidateObject_Object_ValidationContext_ICollection_02 ()56		{57			var dummy = new Dummy ();58			var ctx = new ValidationContext (dummy, null, null);59			var results = new List<ValidationResult> ();60			bool valid = Validator.TryValidateObject (dummy, ctx, results);61			Assert.IsTrue (valid, "#A1-1");62			Assert.AreEqual (0, results.Count, "#A1-2");63			dummy = new Dummy {64				NameField = null65			};66			AssertExtensions.Throws<ArgumentException> (() => {67				// The instance provided must match the ObjectInstance on the ValidationContext supplied.68				valid = Validator.TryValidateObject (dummy, ctx, results);69			}, "#A2");70			// Fields are ignored71			ctx = new ValidationContext (dummy, null, null);72			valid = Validator.TryValidateObject (dummy, ctx, results);73			Assert.IsTrue (valid, "#A3-1");74			Assert.AreEqual (0, results.Count, "#A3-2");75			// Required properties existence is validated76			dummy = new Dummy {77				RequiredDummyField = null78			};79			ctx = new ValidationContext (dummy, null, null);80			valid = Validator.TryValidateObject (dummy, ctx, results);81			Assert.IsTrue (valid, "#A4-1");82			Assert.AreEqual (0, results.Count, "#A4-2");83			dummy = new Dummy {84				RequiredDummyProperty = null85			};86			ctx = new ValidationContext (dummy, null, null);87			valid = Validator.TryValidateObject (dummy, ctx, results);88			Assert.IsFalse (valid, "#A5-1");89			Assert.AreEqual (1, results.Count, "#A5-2");90			results.Clear ();91			// validation attributes other than Required are ignored92			dummy = new Dummy {93				NameProperty = null94			};95			ctx = new ValidationContext (dummy, null, null);96			valid = Validator.TryValidateObject (dummy, ctx, results);97			Assert.IsTrue (valid, "#A6-1");98			Assert.AreEqual (0, results.Count, "#A6-2");99			dummy = new Dummy {100				MinMaxProperty = 0101			};102			ctx = new ValidationContext (dummy, null, null);103			valid = Validator.TryValidateObject (dummy, ctx, results);104			Assert.IsTrue (valid, "#A7-1");105			Assert.AreEqual (0, results.Count, "#A7-2");106			dummy = new Dummy {107				FailValidation = true108			};109			ctx = new ValidationContext (dummy, null, null);110			valid = Validator.TryValidateObject (dummy, ctx, results);111			Assert.IsFalse (valid, "#A8-1");112			Assert.AreEqual (1, results.Count, "#A8-2");113		}114		[Test]115		public void TryValidateObject_Object_ValidationContext_ICollection_Bool_01 ()116		{117			var dummy = new DummyNoAttributes ();118			var ctx = new ValidationContext (dummy, null, null);119			var results = new List<ValidationResult> ();120			AssertExtensions.Throws<ArgumentNullException> (() => {121				Validator.TryValidateObject (null, ctx, results, false);122			}, "#A1-1");123			AssertExtensions.Throws<ArgumentNullException> (() => {124				Validator.TryValidateObject (dummy, null, results, false);125			}, "#A1-2");126			bool valid = Validator.TryValidateObject (dummy, ctx, null, false);127			Assert.IsTrue (valid, "#A2-1");128			Assert.IsTrue (results.Count == 0, "#A2-2");129			valid = Validator.TryValidateObject (dummy, ctx, null, true);130			Assert.IsTrue (valid, "#A3-1");131			Assert.IsTrue (results.Count == 0, "#A3-2");132		}133		[Test]134		public void TryValidateObject_Object_ValidationContext_ICollection_Bool_02 ()135		{136			var dummy = new Dummy ();137			var ctx = new ValidationContext (dummy, null, null);138			var results = new List<ValidationResult> ();139			bool valid = Validator.TryValidateObject (dummy, ctx, results, false);140			Assert.IsTrue (valid, "#A1-1");141			Assert.AreEqual (0, results.Count, "#A1-2");142			valid = Validator.TryValidateObject (dummy, ctx, results, true);143			Assert.IsTrue (valid, "#A1-3");144			Assert.AreEqual (0, results.Count, "#A1-4");145			dummy = new Dummy {146				NameField = null147			};148			AssertExtensions.Throws<ArgumentException> (() => {149				// The instance provided must match the ObjectInstance on the ValidationContext supplied.150				valid = Validator.TryValidateObject (dummy, ctx, results, false);151			}, "#A2-1");152			AssertExtensions.Throws<ArgumentException> (() => {153				// The instance provided must match the ObjectInstance on the ValidationContext supplied.154				valid = Validator.TryValidateObject (dummy, ctx, results, true);155			}, "#A2-2");156			// Fields are ignored157			ctx = new ValidationContext (dummy, null, null);158			valid = Validator.TryValidateObject (dummy, ctx, results, false);159			Assert.IsTrue (valid, "#A3-1");160			Assert.AreEqual (0, results.Count, "#A3-2");161			valid = Validator.TryValidateObject (dummy, ctx, results, true);162			Assert.IsTrue (valid, "#A3-3");163			Assert.AreEqual (0, results.Count, "#A3-4");164			dummy = new Dummy {165				RequiredDummyField = null166			};167			ctx = new ValidationContext (dummy, null, null);168			valid = Validator.TryValidateObject (dummy, ctx, results, false);169			Assert.IsTrue (valid, "#A4-1");170			Assert.AreEqual (0, results.Count, "#A4-2");171			valid = Validator.TryValidateObject (dummy, ctx, results, true);172			Assert.IsTrue (valid, "#A4-3");173			Assert.AreEqual (0, results.Count, "#A4-4");174			// Required properties existence is validated175			dummy = new Dummy {176				RequiredDummyProperty = null177			};178			ctx = new ValidationContext (dummy, null, null);179			valid = Validator.TryValidateObject (dummy, ctx, results, false);180			Assert.IsFalse (valid, "#A5-1");181			Assert.AreEqual (1, results.Count, "#A5-2");182			results.Clear ();183			184			valid = Validator.TryValidateObject (dummy, ctx, results, true);185			Assert.IsFalse (valid, "#A5-3");186			Assert.AreEqual (1, results.Count, "#A5-4");187			results.Clear ();188			dummy = new Dummy {189				NameProperty = null190			};191			ctx = new ValidationContext (dummy, null, null);192			valid = Validator.TryValidateObject (dummy, ctx, results, false);193			Assert.IsTrue (valid, "#A6-1");194			Assert.AreEqual (0, results.Count, "#A6-2");195			// NameProperty is null, that causes the StringLength validator to skip its tests196			valid = Validator.TryValidateObject (dummy, ctx, results, true);197			Assert.IsTrue (valid, "#A6-3");198			Assert.AreEqual (0, results.Count, "#A6-4");199			dummy.NameProperty = "0";200			valid = Validator.TryValidateObject (dummy, ctx, results, true);201			Assert.IsFalse (valid, "#A6-5");202			Assert.AreEqual (1, results.Count, "#A6-6");203			results.Clear ();204			dummy.NameProperty = "name too long (invalid value)";205			valid = Validator.TryValidateObject (dummy, ctx, results, true);206			Assert.IsFalse (valid, "#A6-7");207			Assert.AreEqual (1, results.Count, "#A6-8");208			results.Clear ();209			dummy = new Dummy {210				MinMaxProperty = 0211			};212			ctx = new ValidationContext (dummy, null, null);213			valid = Validator.TryValidateObject (dummy, ctx, results, false);214			Assert.IsTrue (valid, "#A7-1");215			Assert.AreEqual (0, results.Count, "#A7-2");216			valid = Validator.TryValidateObject (dummy, ctx, results, true);217			Assert.IsFalse (valid, "#A7-3");218			Assert.AreEqual (1, results.Count, "#A7-4");219			results.Clear ();220			dummy = new Dummy {221				FailValidation = true222			};223			ctx = new ValidationContext (dummy, null, null);224			valid = Validator.TryValidateObject (dummy, ctx, results, false);225			Assert.IsFalse (valid, "#A8-1");226			Assert.AreEqual (1, results.Count, "#A8-2");227			results.Clear ();228			valid = Validator.TryValidateObject (dummy, ctx, results, true);229			Assert.IsFalse (valid, "#A8-3");230			Assert.AreEqual (1, results.Count, "#A8-4");231			results.Clear ();232			var dummy2 = new DummyWithException ();233			ctx = new ValidationContext (dummy2, null, null);234			AssertExtensions.Throws<ApplicationException> (() => {235				Validator.TryValidateObject (dummy2, ctx, results, true);236			}, "#A9");237		}238		[Test]239		public void TryValidateProperty ()240		{241			var dummy = new DummyNoAttributes ();242			var ctx = new ValidationContext (dummy, null, null) {243				MemberName = "NameProperty"244			};245			var results = new List<ValidationResult> ();246			AssertExtensions.Throws<ArgumentException> (() => {247				// MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty:248				// System.ArgumentException : The type 'DummyNoAttributes' does not contain a public property named 'NameProperty'.249				// Parameter name: propertyName250				//251				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.TypeStoreItem.GetPropertyStoreItem(String propertyName)252				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.GetPropertyType(ValidationContext validationContext)253				// at System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(Object value, ValidationContext validationContext, ICollection`1 validationResults)254				// at MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty() in C:\Users\grendel\Documents\Visual Studio 2010\Projects\System.Web.Test\System.Web.Test\System.ComponentModel.DataAnnotations\ValidatorTest.cs:line 283255				Validator.TryValidateProperty ("dummy", ctx, results);256			}, "#A1-1");257			Assert.AreEqual (0, results.Count, "#A1-2");258			AssertExtensions.Throws<ArgumentNullException> (() => {259				Validator.TryValidateProperty ("dummy", null, results);260			}, "#A1-2");261			var dummy2 = new Dummy ();262			ctx = new ValidationContext (dummy2, null, null) {263				MemberName = "NameProperty"264			};265			266			bool valid = Validator.TryValidateProperty (null, ctx, results);267			Assert.IsTrue (valid, "#A1-3");268			Assert.AreEqual (0, results.Count, "#A1-4");269			ctx = new ValidationContext (dummy2, null, null) {270				MemberName = "MinMaxProperty"271			};272			AssertExtensions.Throws<ArgumentException> (() => {273				Validator.TryValidateProperty (null, ctx, results);274			}, "#A1-5");275			ctx = new ValidationContext (dummy2, null, null);276			AssertExtensions.Throws<ArgumentNullException> (() => {277				// MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty:278				// System.ArgumentNullException : Value cannot be null.279				// Parameter name: propertyName280				//281				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.TypeStoreItem.TryGetPropertyStoreItem(String propertyName, PropertyStoreItem& item)282				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.TypeStoreItem.GetPropertyStoreItem(String propertyName)283				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.GetPropertyType(ValidationContext validationContext)284				// at System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(Object value, ValidationContext validationContext, ICollection`1 validationResults)285				// at MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty() in C:\Users\grendel\Documents\Visual Studio 2010\Projects\System.Web.Test\System.Web.Test\System.ComponentModel.DataAnnotations\ValidatorTest.cs:line 289286				Validator.TryValidateProperty ("dummy", ctx, results);287			}, "#A2-1");288			Assert.AreEqual (0, results.Count, "#A2-2");289			ctx = new ValidationContext (dummy2, null, null) {290				MemberName = String.Empty291			};292			AssertExtensions.Throws<ArgumentNullException> (() => {293				// MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty:294				// System.ArgumentNullException : Value cannot be null.295				// Parameter name: propertyName296				//297				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.TypeStoreItem.TryGetPropertyStoreItem(String propertyName, PropertyStoreItem& item)298				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.TypeStoreItem.GetPropertyStoreItem(String propertyName)299				// at System.ComponentModel.DataAnnotations.ValidationAttributeStore.GetPropertyType(ValidationContext validationContext)300				// at System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(Object value, ValidationContext validationContext, ICollection`1 validationResults)301				// at MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty() in C:\Users\grendel\Documents\Visual Studio 2010\Projects\System.Web.Test\System.Web.Test\System.ComponentModel.DataAnnotations\ValidatorTest.cs:line 289302				Validator.TryValidateProperty ("dummy", ctx, results);303			}, "#A2-2");304			Assert.AreEqual (0, results.Count, "#A2-2");305			dummy2 = new Dummy ();306			ctx = new ValidationContext (dummy2, null, null) {307				MemberName = "NameProperty"308			};309			AssertExtensions.Throws<ArgumentException> (() => {310				// MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty:311				// System.ArgumentException : The value for property 'NameProperty' must be of type 'System.String'.312				// Parameter name: value313				//314				// at System.ComponentModel.DataAnnotations.Validator.EnsureValidPropertyType(String propertyName, Type propertyType, Object value)315				// at System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(Object value, ValidationContext validationContext, ICollection`1 validationResults)316				// at MonoTests.System.ComponentModel.DataAnnotations.ValidatorTest.TryValidateProperty() in C:\Users\grendel\Documents\Visual Studio 2010\Projects\System.Web.Test\System.Web.Test\System.ComponentModel.DataAnnotations\ValidatorTest.cs:line 315317				Validator.TryValidateProperty (1234, ctx, results);318			}, "#A3-1");319			Assert.AreEqual (0, results.Count, "#A3-2");320			dummy2 = new Dummy ();321			ctx = new ValidationContext (dummy2, null, null) {322				MemberName = "NameProperty"323			};324			325			valid = Validator.TryValidateProperty (String.Empty, ctx, results);326			Assert.IsFalse (valid, "#A4-1");327			Assert.AreEqual (1, results.Count, "#A4-2");328			results.Clear ();329			valid = Validator.TryValidateProperty ("this value is way too long", ctx, results);330			Assert.IsFalse (valid, "#A4-3");331			Assert.AreEqual (1, results.Count, "#A4-4");332			results.Clear ();333			valid = Validator.TryValidateProperty ("good value", ctx, results);334			Assert.IsTrue (valid, "#A4-5");335			Assert.AreEqual (0, results.Count, "#A4-6");336			dummy2 = new Dummy ();337			ctx = new ValidationContext (dummy2, null, null) {338				MemberName = "CustomValidatedProperty"339			};340			valid = Validator.TryValidateProperty (String.Empty, ctx, results);341			Assert.IsFalse (valid, "#A5-1");342			Assert.AreEqual (1, results.Count, "#A5-2");343			results.Clear ();344			valid = Validator.TryValidateProperty ("fail", ctx, results);345			Assert.IsFalse (valid, "#A5-3");346			Assert.AreEqual (1, results.Count, "#A5-4");347			results.Clear ();348			valid = Validator.TryValidateProperty ("f", ctx, results);349			Assert.IsFalse (valid, "#A5-5");350			Assert.AreEqual (2, results.Count, "#A5-6");351			results.Clear ();352			valid = Validator.TryValidateProperty ("good value", ctx, results);353			Assert.IsTrue (valid, "#A5-7");354			Assert.AreEqual (0, results.Count, "#A5-8");355		}356		[Test]357		public void TryValidateValue_01 ()358		{359			var dummy = new DummyNoAttributes ();360			var ctx = new ValidationContext (dummy, null, null) {361				MemberName = "NameProperty"362			};363			var results = new List<ValidationResult> ();364			var attributes = new List <ValidationAttribute> ();365			366			bool valid = Validator.TryValidateValue (null, ctx, results, attributes);367			Assert.IsTrue (valid, "#A1-1");368			Assert.AreEqual (0, results.Count, "#A1-2");369			AssertExtensions.Throws<ArgumentNullException> (() => {370				Validator.TryValidateValue ("dummy", null, results, attributes);371			}, "#A2");372			valid = Validator.TryValidateValue ("dummy", ctx, null, attributes);373			Assert.IsTrue (valid, "#A3-1");374			Assert.AreEqual (0, results.Count, "#A3-2");375			AssertExtensions.Throws<ArgumentNullException> (() => {376				Validator.TryValidateValue ("dummy", ctx, results, null);377			}, "#A4");378		}379		[Test]380		public void TryValidateValue_02 ()381		{382			var dummy = new DummyNoAttributes ();383			var ctx = new ValidationContext (dummy, null, null);384			var results = new List<ValidationResult> ();385			var log = new List<string> ();386			var attributes = new List<ValidationAttribute> () {387				new StringLengthAttributePoker (10, log) {388					MinimumLength = 2389				},390				new RequiredAttributePoker (log)391			};392			bool valid = Validator.TryValidateValue (null, ctx, results, attributes);393			Assert.IsFalse (valid, "#A1-1");394			Assert.AreEqual (1, results.Count, "#A1-2");395			Assert.AreEqual (1, log.Count, "#A1-3");396			Assert.IsTrue (log [0].StartsWith ("RequiredAttributePoker.IsValid (object)"), "#A1-4");397			results.Clear ();398			log.Clear ();399			AssertExtensions.Throws<InvalidCastException> (() => {400				// Thrown by StringValidatorAttribute401				Validator.TryValidateValue (1234, ctx, results, attributes);402			}, "#A2-1");403			Assert.AreEqual (0, results.Count, "#A2-2");404			Assert.AreEqual (2, log.Count, "#A2-3");405			Assert.IsTrue (log[0].StartsWith ("RequiredAttributePoker.IsValid (object)"), "#A2-4");406			Assert.IsTrue (log[1].StartsWith ("StringLengthAttributePoker.IsValid (object)"), "#A2-5");407			results.Clear ();408			log.Clear ();409			attributes.Add (new CustomValidationAttribute (typeof (ValidatorTest), "ValueValidationMethod"));410			attributes.Add (new CustomValidationAttribute (typeof (ValidatorTest), "ValueValidationMethod"));411			valid = Validator.TryValidateValue ("test", ctx, results, attributes);412			Assert.IsFalse (valid, "#A3-1");413			Assert.AreEqual (2, results.Count, "#A3-2");414			Assert.AreEqual (2, log.Count, "#A3-3");415			Assert.IsTrue (log[0].StartsWith ("RequiredAttributePoker.IsValid (object)"), "#A3-4");416			Assert.IsTrue (log[1].StartsWith ("StringLengthAttributePoker.IsValid (object)"), "#A3-5");417			Assert.AreEqual ("ValueValidationMethod", results[0].ErrorMessage, "#A3-6");418			Assert.AreEqual ("ValueValidationMethod", results[1].ErrorMessage, "#A3-7");419			results.Clear ();420			log.Clear ();421			attributes.RemoveAt (2);422			attributes.RemoveAt (2);423			AssertExtensions.Throws<ArgumentNullException> (() => {424				Validator.TryValidateValue ("dummy", null, results, attributes);425			}, "#B1");426			valid = Validator.TryValidateValue ("dummy", ctx, null, attributes);427			Assert.IsTrue (valid, "#B2-1");428			Assert.AreEqual (0, results.Count, "#B2-2");429			AssertExtensions.Throws<ArgumentNullException> (() => {430				Validator.TryValidateValue ("dummy", ctx, results, null);431			}, "#B3");432		}433		[Test]434		public void ValidateObject_Object_ValidationContext_01 ()435		{436			var dummy = new DummyNoAttributes ();437			var ctx = new ValidationContext (dummy, null, null);438			439			AssertExtensions.Throws<ArgumentNullException> (() => {440				Validator.ValidateObject (null, ctx);441			}, "#A1-1");442			AssertExtensions.Throws<ArgumentNullException> (() => {443				Validator.ValidateObject (dummy, null);444			}, "#A1-2");445			try {446				Validator.ValidateObject (dummy, ctx);447			} catch (Exception ex) {448				Assert.Fail ("#A2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);449			}450		}451		[Test]452		public void ValidateObject_Object_ValidationContext_02 ()453		{454			var dummy = new Dummy ();455			var ctx = new ValidationContext (dummy, null, null);456			try {457				Validator.ValidateObject (dummy, ctx);458			} catch (Exception ex) {459				Assert.Fail ("#A1 (exception {0} thrown: {1})", ex.GetType (), ex.Message);460			}461			dummy = new Dummy {462				NameField = null463			};464			AssertExtensions.Throws<ArgumentException> (() => {465				// The instance provided must match the ObjectInstance on the ValidationContext supplied.466				Validator.ValidateObject (dummy, ctx);467			}, "#A2");468			// Fields are ignored469			ctx = new ValidationContext (dummy, null, null);470			try {471				Validator.ValidateObject (dummy, ctx);472			}  catch (Exception ex) {473				Assert.Fail ("#A3 (exception {0} thrown: {1})", ex.GetType (), ex.Message);474			}475			476			dummy = new Dummy {477				RequiredDummyField = null478			};479			ctx = new ValidationContext (dummy, null, null);480			try {481				Validator.ValidateObject (dummy, ctx);482			} catch (Exception ex) {483				Assert.Fail ("#A4 (exception {0} thrown: {1})", ex.GetType (), ex.Message);484			}485			dummy = new Dummy {486				RequiredDummyProperty = null487			};488			ctx = new ValidationContext (dummy, null, null);489			AssertExtensions.Throws<ValidationException> (() => {490				Validator.ValidateObject (dummy, ctx);491			}, "#A5");492			// validation attributes other than Required are ignored493			dummy = new Dummy {494				NameProperty = null495			};496			ctx = new ValidationContext (dummy, null, null);497			try {498				Validator.ValidateObject (dummy, ctx);499			} catch (Exception ex) {500				Assert.Fail ("#A6 (exception {0} thrown: {1})", ex.GetType (), ex.Message);501			}502			503			dummy = new Dummy {504				MinMaxProperty = 0505			};506			ctx = new ValidationContext (dummy, null, null);507			try {508				Validator.ValidateObject (dummy, ctx);509			} catch (Exception ex) {510				Assert.Fail ("#A7 (exception {0} thrown: {1})", ex.GetType (), ex.Message);511			}512			dummy = new Dummy {513				FailValidation = true514			};515			ctx = new ValidationContext (dummy, null, null);516			AssertExtensions.Throws<ValidationException> (() => {517				Validator.ValidateObject (dummy, ctx);518			}, "#A8");519			var dummy2 = new DummyMultipleCustomValidators ();520			ctx = new ValidationContext (dummy2, null, null);521			try {522				Validator.ValidateObject (dummy2, ctx);523			} catch (Exception ex) {524				Assert.Fail ("#A9 (exception {0} thrown: {1})", ex.GetType (), ex.Message);525			}526		}527		[Test]528		public void ValidateObject_Object_ValidationContext_Bool_01 ()529		{530			var dummy = new DummyNoAttributes ();531			var ctx = new ValidationContext (dummy, null, null);532			AssertExtensions.Throws<ArgumentNullException> (() => {533				Validator.ValidateObject (null, ctx, false);534			}, "#A1-1");535			AssertExtensions.Throws<ArgumentNullException> (() => {536				Validator.ValidateObject (dummy, null, false);537			}, "#A1-2");538			try {539				Validator.ValidateObject (dummy, ctx, false);540			} catch (Exception ex) {541				Assert.Fail ("#A2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);542			}543			try {544				Validator.ValidateObject (dummy, ctx, true);545			} catch (Exception ex) {546				Assert.Fail ("#A3 (exception {0} thrown: {1})", ex.GetType (), ex.Message);547			}548		}549		[Test]550		public void ValidateObject_Object_ValidationContext_Bool_02 ()551		{552			var dummy = new Dummy ();553			var ctx = new ValidationContext (dummy, null, null);554			try {555				Validator.ValidateObject (dummy, ctx, false);556			} catch (Exception ex) {557				Assert.Fail ("#A1 (exception {0} thrown: {1})", ex.GetType (), ex.Message);558			}559			try {560				Validator.ValidateObject (dummy, ctx, true);561			} catch (Exception ex) {562				Assert.Fail ("#A2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);563			}564			dummy = new Dummy {565				NameField = null566			};567			AssertExtensions.Throws<ArgumentException> (() => {568				// The instance provided must match the ObjectInstance on the ValidationContext supplied.569				Validator.ValidateObject (dummy, ctx, false);570			}, "#A3-1");571			AssertExtensions.Throws<ArgumentException> (() => {572				// The instance provided must match the ObjectInstance on the ValidationContext supplied.573				Validator.ValidateObject (dummy, ctx, true);574			}, "#A3-2");575			// Fields are ignored576			ctx = new ValidationContext (dummy, null, null);577			try {578				Validator.ValidateObject (dummy, ctx, false);579			} catch (Exception ex) {580				Assert.Fail ("#A4-1 (exception {0} thrown: {1})", ex.GetType (), ex.Message);581			}582			try {583				Validator.ValidateObject (dummy, ctx, true);584			} catch (Exception ex) {585				Assert.Fail ("#A4-2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);586			}587			dummy = new Dummy {588				RequiredDummyField = null589			};590			ctx = new ValidationContext (dummy, null, null);591			try {592				Validator.ValidateObject (dummy, ctx, false);593			} catch (Exception ex) {594				Assert.Fail ("#A5-1 (exception {0} thrown: {1})", ex.GetType (), ex.Message);595			}596			try {597				Validator.ValidateObject (dummy, ctx, true);598			} catch (Exception ex) {599				Assert.Fail ("#A5-2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);600			}601			// Required properties existence is validated602			dummy = new Dummy {603				RequiredDummyProperty = null604			};605			ctx = new ValidationContext (dummy, null, null);606			AssertExtensions.Throws<ValidationException> (() => {607				Validator.ValidateObject (dummy, ctx, false);608			}, "#A6-1");609			AssertExtensions.Throws<ValidationException> (() => {610				Validator.ValidateObject (dummy, ctx, true);611			}, "#A6-2");612			dummy = new Dummy {613				NameProperty = null614			};615			ctx = new ValidationContext (dummy, null, null);616			try {617				Validator.ValidateObject (dummy, ctx, false);618			} catch (Exception ex) {619				Assert.Fail ("#A7 (exception {0} thrown: {1})", ex.GetType (), ex.Message);620			}621			// NameProperty is null, that causes the StringLength validator to skip its tests622			try {623				Validator.ValidateObject (dummy, ctx, true);624			} catch (Exception ex) {625				Assert.Fail ("#A8 (exception {0} thrown: {1})", ex.GetType (), ex.Message);626			}627			dummy.NameProperty = "0";628			AssertExtensions.Throws<ValidationException> (() => {629				Validator.ValidateObject (dummy, ctx, true);630			}, "#A9");631			dummy.NameProperty = "name too long (invalid value)";632			AssertExtensions.Throws<ValidationException> (() => {633				Validator.ValidateObject (dummy, ctx, true);634			}, "#A10");635			dummy = new Dummy {636				MinMaxProperty = 0637			};638			ctx = new ValidationContext (dummy, null, null);639			try {640				Validator.ValidateObject (dummy, ctx, false);641			} catch (Exception ex) {642				Assert.Fail ("#A11 (exception {0} thrown: {1})", ex.GetType (), ex.Message);643			}644			AssertExtensions.Throws<ValidationException> (() => {645				Validator.ValidateObject (dummy, ctx, true);646			}, "#A12");647			dummy = new Dummy {648				FailValidation = true649			};650			ctx = new ValidationContext (dummy, null, null);651			AssertExtensions.Throws<ValidationException> (() => {652				Validator.ValidateObject (dummy, ctx, false);653			}, "#A13-1");654			AssertExtensions.Throws<ValidationException> (() => {655				Validator.ValidateObject (dummy, ctx, true);656			}, "#A13-2");657			var dummy2 = new DummyWithException ();658			ctx = new ValidationContext (dummy2, null, null);659			AssertExtensions.Throws<ApplicationException> (() => {660				Validator.ValidateObject (dummy2, ctx, true);661			}, "#A14");662			var dummy3 = new DummyMultipleCustomValidators ();663			ctx = new ValidationContext (dummy3, null, null);664			try {665				Validator.ValidateObject (dummy3, ctx, false);666			} catch (Exception ex) {667				Assert.Fail ("#A9 (exception {0} thrown: {1})", ex.GetType (), ex.Message);668			}669			try {670				Validator.ValidateObject (dummy3, ctx, true);671			} catch (ValidationException ex) {672				Assert.AreEqual ("FirstPropertyValidationMethod", ex.Message, "#A10");673			} catch (Exception ex) {674				Assert.Fail ("#A10 (exception {0} thrown: {1})", ex.GetType (), ex.Message);675			}676		}677		[Test]678		public void ValidateProperty ()679		{680			var dummy = new DummyNoAttributes ();681			var ctx = new ValidationContext (dummy, null, null) {682				MemberName = "NameProperty"683			};684			AssertExtensions.Throws<ArgumentException> (() => {685				Validator.ValidateProperty ("dummy", ctx);686			}, "#A1-1");687			AssertExtensions.Throws<ArgumentNullException> (() => {688				Validator.ValidateProperty ("dummy", null);689			}, "#A1-2");690			var dummy2 = new Dummy ();691			ctx = new ValidationContext (dummy2, null, null) {692				MemberName = "NameProperty"693			};694			try {695				Validator.ValidateProperty (null, ctx);696			} catch (Exception ex) {697				Assert.Fail ("#A2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);698			}699			ctx = new ValidationContext (dummy2, null, null) {700				MemberName = "MinMaxProperty"701			};702			AssertExtensions.Throws<ArgumentException> (() => {703				Validator.ValidateProperty (null, ctx);704			}, "#A3");705			ctx = new ValidationContext (dummy2, null, null);706			AssertExtensions.Throws<ArgumentNullException> (() => {707				Validator.ValidateProperty ("dummy", ctx);708			}, "#A4");709			ctx = new ValidationContext (dummy2, null, null) {710				MemberName = String.Empty711			};712			AssertExtensions.Throws<ArgumentNullException> (() => {713				Validator.ValidateProperty ("dummy", ctx);714			}, "#A5");715			dummy2 = new Dummy ();716			ctx = new ValidationContext (dummy2, null, null) {717				MemberName = "NameProperty"718			};719			AssertExtensions.Throws<ArgumentException> (() => {720				Validator.ValidateProperty (1234, ctx);721			}, "#A6");722			dummy2 = new Dummy ();723			ctx = new ValidationContext (dummy2, null, null) {724				MemberName = "NameProperty"725			};726			AssertExtensions.Throws<ValidationException> (() => {727				Validator.ValidateProperty (String.Empty, ctx);728			}, "#A7");729			AssertExtensions.Throws<ValidationException> (() => {730				Validator.ValidateProperty ("this value is way too long", ctx);731			}, "#A8");732			try {733				Validator.ValidateProperty ("good value", ctx);734			} catch (Exception ex) {735				Assert.Fail ("#A9 (exception {0} thrown: {1})", ex.GetType (), ex.Message);736			}737			dummy2 = new Dummy ();738			ctx = new ValidationContext (dummy2, null, null) {739				MemberName = "CustomValidatedProperty"740			};741			AssertExtensions.Throws<ValidationException> (() => {742				Validator.ValidateProperty (String.Empty, ctx);743			}, "#A10");744			AssertExtensions.Throws<ValidationException> (() => {745				Validator.ValidateProperty ("fail", ctx);746			}, "#A11");747			AssertExtensions.Throws<ValidationException> (() => {748				Validator.ValidateProperty ("f", ctx);749			}, "#A12");750			try {751				Validator.ValidateProperty ("good value", ctx);752			} catch (Exception ex) {753				Assert.Fail ("#A13 (exception {0} thrown: {1})", ex.GetType (), ex.Message);754			}755		}756		[Test]757		public void ValidateValue_01 ()758		{759			var dummy = new DummyNoAttributes ();760			var ctx = new ValidationContext (dummy, null, null) {761				MemberName = "NameProperty"762			};763			var attributes = new List<ValidationAttribute> ();764			try {765				Validator.ValidateValue (null, ctx, attributes);766			} catch (Exception ex) {767				Assert.Fail ("#A1 (exception {0} thrown: {1})", ex.GetType (), ex.Message);768			}769			AssertExtensions.Throws<ArgumentNullException> (() => {770				Validator.ValidateValue ("dummy", null, attributes);771			}, "#A2");772			try {773				Validator.ValidateValue ("dummy", ctx, attributes);774			} catch (Exception ex) {775				Assert.Fail ("#A3 (exception {0} thrown: {1})", ex.GetType (), ex.Message);776			}777			AssertExtensions.Throws<ArgumentNullException> (() => {778				Validator.ValidateValue ("dummy", ctx, null);779			}, "#A4");780		}781		[Test]782		public void ValidateValue_02 ()783		{784			var dummy = new DummyNoAttributes ();785			var ctx = new ValidationContext (dummy, null, null);786			var log = new List<string> ();787			var attributes = new List<ValidationAttribute> () {788				new StringLengthAttributePoker (10, log) {789					MinimumLength = 2790				},791				new RequiredAttributePoker (log)792			};793			AssertExtensions.Throws<ValidationException> (() => {794				Validator.ValidateValue (null, ctx, attributes);795			}, "#A1-1");796			Assert.AreEqual (1, log.Count, "#A1-2");797			Assert.IsTrue (log[0].StartsWith ("RequiredAttributePoker.IsValid (object)"), "#A1-3");798			log.Clear ();799			AssertExtensions.Throws<InvalidCastException> (() => {800				// Thrown by StringValidatorAttribute801				Validator.ValidateValue (1234, ctx, attributes);802			}, "#A2-1");;803			Assert.AreEqual (2, log.Count, "#A2-2");804			Assert.IsTrue (log[0].StartsWith ("RequiredAttributePoker.IsValid (object)"), "#A2-3");805			Assert.IsTrue (log[1].StartsWith ("StringLengthAttributePoker.IsValid (object)"), "#A2-4");806			log.Clear ();807			attributes.Add (new CustomValidationAttribute (typeof (ValidatorTest), "ValueValidationMethod"));808			attributes.Add (new CustomValidationAttribute (typeof (ValidatorTest), "ValueValidationMethod"));809			AssertExtensions.Throws<ValidationException> (() => {810				Validator.ValidateValue ("test", ctx, attributes);811			}, "#A3-1");812			Assert.AreEqual (2, log.Count, "#A3-2");813			Assert.IsTrue (log[0].StartsWith ("RequiredAttributePoker.IsValid (object)"), "#A3-3");814			Assert.IsTrue (log[1].StartsWith ("StringLengthAttributePoker.IsValid (object)"), "#A3-4");815			log.Clear ();816			attributes.RemoveAt (2);817			attributes.RemoveAt (2);818			AssertExtensions.Throws<ArgumentNullException> (() => {819				Validator.ValidateValue ("dummy", null, attributes);820			}, "#B1");821			try {822				Validator.ValidateValue ("dummy", ctx, attributes);823			} catch (Exception ex) {824				Assert.Fail ("#B2 (exception {0} thrown: {1})", ex.GetType (), ex.Message);825			}826			AssertExtensions.Throws<ArgumentNullException> (() => {827				Validator.ValidateValue ("dummy", ctx, null);828			}, "#B3");829		}830		831		[Test]832		public void TryValidateValue_Throws_ValidationException_When_Property_Is_NullableAndRequired_And_Value_Is_Null ()833		{834			EntityMock entity = new EntityMock ();835			ICollection<ValidationResult> result = new List<ValidationResult>();836			ICollection<ValidationAttribute> attributes = new List<ValidationAttribute> ();837			attributes.Add (new RequiredAttribute ());838			// Year = null839			bool isValid = Validator.TryValidateValue (null, new ValidationContext (entity, null, null) { MemberName = "Year" }, result, attributes);840			Assert.IsFalse (isValid, "#A1-1");841			Assert.AreEqual (1, result.Count, "#A1-2");842			// Name = null, string843			result.Clear ();844			isValid = Validator.TryValidateValue (null, new ValidationContext (entity, null, null) { MemberName =  "Name" }, result, attributes);845			Assert.IsFalse (isValid, "#A2-1");846			Assert.AreEqual (1, result.Count, "#A2-2");847			// Name = string.Empty, string848			result.Clear ();849			isValid = Validator.TryValidateValue (String.Empty, new ValidationContext (entity, null, null) { MemberName = "Name" }, result, attributes);850			Assert.IsFalse (isValid, "#A3-1");851			Assert.AreEqual (1, result.Count, "#A3-2");852		}853		[Test]854		public void TryValidateProperty_Throws_ValidationException_When_Property_Is_NullableAndRequired_And_Value_Is_Null ()855		{856			EntityMock entity = new EntityMock ();857			ICollection<ValidationResult> result = new List<ValidationResult> ();858			// Year = null859			bool isValid = Validator.TryValidateProperty (null, new ValidationContext (entity, null, null) { MemberName = "Year" }, result);860			Assert.IsFalse (isValid, "#A1-1");861			Assert.AreEqual (1, result.Count, "#A1-2");862			// Name = null, string863			result.Clear ();864			isValid = Validator.TryValidateProperty (null, new ValidationContext (entity, null, null) { MemberName = "Name" }, result);865			Assert.IsFalse (isValid, "#A2-1");866			Assert.AreEqual (1, result.Count, "#A2-2");867			// Name = string.Empty, string868			result.Clear ();869			isValid = Validator.TryValidateProperty (String.Empty, new ValidationContext (entity, null, null) { MemberName = "Name" }, result);870			Assert.IsFalse (isValid, "#A3-1");871			Assert.AreEqual (1, result.Count, "#A3-2");872		}873		[Test]874		public void TryValidateObject_Throws_ValidationException_When_Property_Is_NullableAndRequired_And_Value_Is_Null ()875		{876			EntityMock entity = new EntityMock ();877			ICollection<ValidationResult> result = new List<ValidationResult> ();878			// Year = null879			bool isValid = Validator.TryValidateObject (entity, new ValidationContext (entity, null, null), result);880			Assert.IsFalse (isValid, "#A1-1");881			Assert.AreEqual (2, result.Count, "#A1-2");882			// Name = null, string883			result.Clear ();884			isValid = Validator.TryValidateObject (entity, new ValidationContext (entity, null, null), result);885			Assert.IsFalse (isValid, "#A2-1");886			Assert.AreEqual (2, result.Count, "#A2-2");887			// Name = string.Empty, string888			result.Clear ();889			entity.Name = String.Empty;890			isValid = Validator.TryValidateObject (entity, new ValidationContext (entity, null, null), result);891			Assert.IsFalse (isValid, "#A3-1");892			Assert.AreEqual (2, result.Count, "#A3-2");893		}894		public static ValidationResult DummyValidationMethod (object o)895		{896			var dummy = o as Dummy;897			if (dummy == null)898				return new ValidationResult ("Invalid DummyValidationMethod input - broken test?");899			if (dummy.FailValidation)900				return new ValidationResult ("Dummy validation failed.");901			return ValidationResult.Success;902		}903		public static ValidationResult CustomValidatedPropertyValidationMethod (object o)904		{905			var dummy = o as string;906			if (dummy != null && (dummy == "f" || dummy == "fail"))907				return new ValidationResult ("Dummy.CustomValidatedProperty validation failed.");908			return ValidationResult.Success;909		}910		public static ValidationResult ValidationMethodException (object o)911		{912			throw new ApplicationException ("SNAFU");913		}914		public static ValidationResult ValueValidationMethod (object o, ValidationContext validationContext)915		{916			return new ValidationResult ("ValueValidationMethod");917		}918		public static ValidationResult FirstPropertyValidationMethod (object o, ValidationContext validationContext)919		{920			return new ValidationResult ("FirstPropertyValidationMethod");921		}922		public static ValidationResult SecondPropertyValidationMethod (object o, ValidationContext validationContext)923		{924			return new ValidationResult ("SecondPropertyValidationMethod");925		}926		public class RequiredAttributePoker : RequiredAttribute927		{928			List <string> log;929			public RequiredAttributePoker (List<string> log)930			{931				if (log == null)932					throw new ArgumentNullException ("log");933				this.log = log;934			}935			public override bool IsValid (object value)936			{937				log.Add ("RequiredAttributePoker.IsValid (object)");938				return base.IsValid (value);939			}940		}941		public class StringLengthAttributePoker : StringLengthAttribute942		{943			List <string> log;944			public StringLengthAttributePoker (int maximumLength, List<string> log)945				: base (maximumLength)946			{947				if (log == null)948					throw new ArgumentNullException ("log");949				this.log = log;950			}951			public override bool IsValid (object value)952			{953				log.Add ("StringLengthAttributePoker.IsValid (object)");954				return base.IsValid (value);955			}956		}957		class DummyNoAttributes958		{ }959		[CustomValidation (typeof (ValidatorTest), "DummyValidationMethod")]960		class Dummy961		{962			[StringLength (10, MinimumLength=2)]963			public string NameField;964			[Required]965			public DummyNoAttributes RequiredDummyField;966			[StringLength (10, MinimumLength = 2)]967			public string NameProperty { get; set; }968			[Required]969			public DummyNoAttributes RequiredDummyProperty { get; set; }970			971			[global::System.ComponentModel.DataAnnotations.RangeAttribute ((int)1, (int)10)]972			public int MinMaxProperty { get; set; }973			[StringLength (10, MinimumLength = 2)]974			[CustomValidation (typeof (ValidatorTest), "CustomValidatedPropertyValidationMethod")]975			public string CustomValidatedProperty { get; set; }976			[CustomValidation (typeof (ValidatorTest), "CustomValidatedPropertyValidationMethod")]977			[StringLength (10, MinimumLength = 2)]978			public string AnotherCustomValidatedProperty { get; set; }979			public bool FailValidation { get; set; }980			public Dummy ()981			{982				NameField = "name";983				NameProperty = "name";984				RequiredDummyField = new DummyNoAttributes ();985				RequiredDummyProperty = new DummyNoAttributes ();986				MinMaxProperty = 5;987				AnotherCustomValidatedProperty = "I'm valid";988			}989		}990		class DummyWithException991		{992			[CustomValidation (typeof (ValidatorTest), "ValidationMethodException")]993			public string AnotherCustomValidatedProperty { get; set; }994		}995		class DummyForValueValidation996		{997			public string DummyNoAttributes;998			public DummyForValueValidation ()999			{1000				this.DummyNoAttributes = "I am valid";1001			}1002		}1003		class DummyMultipleCustomValidators1004		{1005			[CustomValidation (typeof (ValidatorTest), "FirstPropertyValidationMethod")]1006			public string FirstProperty { get; set; }1007			[CustomValidation (typeof (ValidatorTest), "SecondPropertyValidationMethod")]1008			public string SecondProperty { get; set; }1009		}1010		1011		class EntityMock1012		{1013			private int? _year;1014			[Required]1015			public int? Year1016			{1017				get { return _year; }...

Full Screen

Full Screen

PrinterFactory.cs

Source:PrinterFactory.cs Github

copy

Full Screen

...42		{43			return new Printer<Label, Source, Dest, Context, EdgeData> (ilDecoder, metaDataProvider, sourceToString, destToString).PrintCodeAt;44		}45		#region Nested type: Printer46		private class Printer<Label, Source, Dest, Context, EdgeData> : IILVisitor<Label, Source, Dest, TextWriter, Dummy> {47			private readonly Func<Dest, string> dest_to_string;48			private readonly IILDecoder<Label, Source, Dest, Context, EdgeData> il_decoder;49			private readonly IMetaDataProvider meta_data_provider;50			private readonly Func<Source, string> source_to_string;51			private string prefix = "";52			public Printer (IILDecoder<Label, Source, Dest, Context, EdgeData> ilDecoder, IMetaDataProvider metaDataProvider,53			                Func<Source, string> sourceToString, Func<Dest, string> destToString)54			{55				this.il_decoder = ilDecoder;56				this.meta_data_provider = metaDataProvider;57				this.source_to_string = sourceToString;58				this.dest_to_string = destToString;59			}60			#region IILVisitor<Label,Source,Dest,TextWriter,Dummy> Members61			public Dummy Binary (Label pc, BinaryOperator op, Dest dest, Source operand1, Source operand2, TextWriter data)62			{63				data.WriteLine ("{0}{1} = {2} {3} {4}", this.prefix, DestName (dest), SourceName (operand1), op.ToString (), SourceName (operand2));64				return Dummy.Value;65			}66			public Dummy Isinst (Label pc, TypeNode type, Dest dest, Source obj, TextWriter data)67			{68				data.WriteLine ("{0}{2} = isinst {1} {3}", this.prefix, this.meta_data_provider.FullName (type), DestName (dest), SourceName (obj));69				return Dummy.Value;70			}71			public Dummy LoadNull (Label pc, Dest dest, TextWriter polarity)72			{73				polarity.WriteLine ("{0}{1} = ldnull", this.prefix, DestName (dest));74				return Dummy.Value;75			}76			public Dummy LoadConst (Label pc, TypeNode type, object constant, Dest dest, TextWriter data)77			{78				data.WriteLine ("{0}{2} = ldc ({3}) '{1}'", this.prefix, constant, DestName (dest), this.meta_data_provider.FullName (type));79				return Dummy.Value;80			}81			public Dummy Sizeof (Label pc, TypeNode type, Dest dest, TextWriter data)82			{83				data.WriteLine ("{0}{2} = sizeof {1}", this.prefix, this.meta_data_provider.FullName (type), DestName (dest));84				return Dummy.Value;85			}86			public Dummy Unary (Label pc, UnaryOperator op, bool unsigned, Dest dest, Source source, TextWriter data)87			{88				data.WriteLine ("{0}{3} = {2}{1} {4}", this.prefix, unsigned ? "_un" : null, op, DestName (dest), SourceName (source));89				return Dummy.Value;90			}91			public Dummy Entry (Label pc, Method method, TextWriter data)92			{93				data.WriteLine ("{0}method_entry {1}", this.prefix, this.meta_data_provider.FullName (method));94				return Dummy.Value;95			}96			public Dummy Assume (Label pc, EdgeTag tag, Source condition, TextWriter data)97			{98				data.WriteLine ("{0}assume({1}) {2}", this.prefix, tag, SourceName (condition));99				return Dummy.Value;100			}101			public Dummy Assert (Label pc, EdgeTag tag, Source condition, TextWriter data)102			{103				data.WriteLine ("{0}assert({1}) {2}", this.prefix, tag, SourceName (condition));104				return Dummy.Value;105			}106			public Dummy BeginOld (Label pc, Label matchingEnd, TextWriter data)107			{108				throw new NotImplementedException ();109			}110			public Dummy EndOld (Label pc, Label matchingBegin, TypeNode type, Dest dest, Source source, TextWriter data)111			{112				throw new NotImplementedException ();113			}114			public Dummy LoadStack (Label pc, int offset, Dest dest, Source source, bool isOld, TextWriter data)115			{116				data.WriteLine ("{0}{1} = {4}ldstack.{2} {3}", this.prefix, DestName (dest), offset, SourceName (source), isOld ? "old." : null);117				return Dummy.Value;118			}119			public Dummy LoadStackAddress (Label pc, int offset, Dest dest, Source source, TypeNode type, bool isOld, TextWriter data)120			{121				data.WriteLine ("{0}{1} = {4}ldstacka.{2} {3}", this.prefix, DestName (dest), offset, SourceName (source), isOld ? "old." : null);122				return Dummy.Value;123			}124			public Dummy LoadResult (Label pc, TypeNode type, Dest dest, Source source, TextWriter data)125			{126				data.WriteLine ("{0}{1} = ldresult {2}", this.prefix, DestName (dest), SourceName (source));127				return Dummy.Value;128			}129			public Dummy Arglist (Label pc, Dest dest, TextWriter data)130			{131				throw new NotImplementedException ();132			}133			public Dummy Branch (Label pc, Label target, bool leavesExceptionBlock, TextWriter data)134			{135				data.WriteLine ("{0}branch", this.prefix);136				return Dummy.Value;137			}138			public Dummy BranchCond (Label pc, Label target, BranchOperator bop, Source value1, Source value2, TextWriter data)139			{140				data.WriteLine ("{0}br.{1} {2},{3}", this.prefix, bop, SourceName (value1), SourceName (value2));141				return Dummy.Value;142			}143			public Dummy BranchTrue (Label pc, Label target, Source cond, TextWriter data)144			{145				data.WriteLine ("{0}br.true {1}", this.prefix, SourceName (cond));146				return Dummy.Value;147			}148			public Dummy BranchFalse (Label pc, Label target, Source cond, TextWriter data)149			{150				data.WriteLine ("{0}br.false {1}", this.prefix, SourceName (cond));151				return Dummy.Value;152			}153			public Dummy Break (Label pc, TextWriter data)154			{155				data.WriteLine ("{0}break", this.prefix);156				return Dummy.Value;157			}158			public Dummy Call<TypeList, ArgList> (Label pc, Method method, bool virt, TypeList extraVarargs, Dest dest, ArgList args, TextWriter data) where TypeList : IIndexable<TypeNode>159				where ArgList : IIndexable<Source>160			{161				data.Write ("{0}{3} = call{2} {1}(", this.prefix, this.meta_data_provider.FullName (method), virt ? "virt" : null, DestName (dest));162				if (args != null) {163					for (int i = 0; i < args.Count; i++)164						data.Write ("{0} ", SourceName (args [i]));165				}166				data.WriteLine (")");167				return Dummy.Value;168			}169			public Dummy Calli<TypeList, ArgList> (Label pc, TypeNode returnType, TypeList argTypes, bool instance, Dest dest, Source functionPointer, ArgList args, TextWriter data)170				where TypeList : IIndexable<TypeNode> where ArgList : IIndexable<Source>171			{172				data.Write ("{0}{1} = calli {2}(", this.prefix, DestName (dest), SourceName (functionPointer));173				if (args != null) {174					for (int i = 0; i < args.Count; i++)175						data.Write ("{0} ", SourceName (args [i]));176				}177				data.WriteLine (")");178				return Dummy.Value;179			}180			public Dummy CheckFinite (Label pc, Dest dest, Source source, TextWriter data)181			{182				data.WriteLine ("{0}{1} = chfinite {2}", this.prefix, DestName (dest), SourceName (source));183				return Dummy.Value;184			}185			public Dummy CopyBlock (Label pc, Source destAddress, Source srcAddress, Source len, TextWriter data)186			{187				data.WriteLine ("{0}cpblk {1} {2} {3}", this.prefix, SourceName (destAddress), SourceName (srcAddress), SourceName (len));188				return Dummy.Value;189			}190			public Dummy EndFilter (Label pc, Source decision, TextWriter data)191			{192				throw new NotImplementedException ();193			}194			public Dummy EndFinally (Label pc, TextWriter data)195			{196				throw new NotImplementedException ();197			}198			public Dummy Jmp (Label pc, Method method, TextWriter data)199			{200				throw new NotImplementedException ();201			}202			public Dummy LoadArg (Label pc, Parameter argument, bool isOld, Dest dest, TextWriter data)203			{204				data.WriteLine ("{0}{2} = {3}ldarg {1}", this.prefix, this.meta_data_provider.Name (argument), DestName (dest), isOld ? "old." : null);205				return Dummy.Value;206			}207			public Dummy LoadArgAddress (Label pc, Parameter argument, bool isOld, Dest dest, TextWriter data)208			{209				data.WriteLine ("{0}{2} = {3}ldarga {1}", this.prefix, this.meta_data_provider.Name (argument), DestName (dest), isOld ? "old." : null);210				return Dummy.Value;211			}212			public Dummy LoadLocal (Label pc, Local local, Dest dest, TextWriter data)213			{214				data.WriteLine ("{0}{2} = ldloc {1}", this.prefix, this.meta_data_provider.Name (local), DestName (dest));215				return Dummy.Value;216			}217			public Dummy LoadLocalAddress (Label pc, Local local, Dest dest, TextWriter data)218			{219				data.WriteLine ("{0}{2} = ldloca {1}", this.prefix, this.meta_data_provider.Name (local), DestName (dest));220				return Dummy.Value;221			}222			public Dummy Nop (Label pc, TextWriter data)223			{224				data.WriteLine ("{0}nop", this.prefix);225				return Dummy.Value;226			}227			public Dummy Pop (Label pc, Source source, TextWriter data)228			{229				data.WriteLine ("{0}pop {1}", this.prefix, SourceName (source));230				return Dummy.Value;231			}232			public Dummy Return (Label pc, Source source, TextWriter data)233			{234				data.WriteLine ("{0}ret {1}", this.prefix, SourceName (source));235				return Dummy.Value;236			}237			public Dummy StoreArg (Label pc, Parameter argument, Source source, TextWriter data)238			{239				data.WriteLine ("{0}starg {1} {2}", this.prefix, this.meta_data_provider.Name (argument), SourceName (source));240				return Dummy.Value;241			}242			public Dummy StoreLocal (Label pc, Local local, Source source, TextWriter data)243			{244				data.WriteLine ("{0}stloc {1} {2}", this.prefix, this.meta_data_provider.Name (local), SourceName (source));245				return Dummy.Value;246			}247			public Dummy Switch (Label pc, TypeNode type, IEnumerable<Pair<object, Label>> cases, Source value, TextWriter data)248			{249				data.WriteLine ("{0}switch {1}", this.prefix, SourceName (value));250				return Dummy.Value;251			}252			public Dummy Box (Label pc, TypeNode type, Dest dest, Source source, TextWriter data)253			{254				data.WriteLine ("{0}{2} = box {1} {3}", this.prefix, this.meta_data_provider.FullName (type), DestName (dest), SourceName (source));255				return Dummy.Value;256			}257			public Dummy ConstrainedCallvirt<TypeList, ArgList> (Label pc, Method method, TypeNode constraint, TypeList extraVarargs, Dest dest, ArgList args, TextWriter data)258				where TypeList : IIndexable<TypeNode> where ArgList : IIndexable<Source>259			{260				data.Write ("{0}{3} = constrained({1}).callvirt {2}(", this.prefix, this.meta_data_provider.FullName (constraint), this.meta_data_provider.FullName (method), DestName (dest));261				if (args != null) {262					for (int i = 0; i < args.Count; i++)263						data.Write ("{0} ", SourceName (args [i]));264				}265				data.WriteLine (")");266				return Dummy.Value;267			}268			public Dummy CastClass (Label pc, TypeNode type, Dest dest, Source obj, TextWriter data)269			{270				data.WriteLine ("{0}{2} = castclass {1} {3}", this.prefix, this.meta_data_provider.FullName (type), DestName (dest), SourceName (obj));271				return Dummy.Value;272			}273			public Dummy CopyObj (Label pc, TypeNode type, Source destPtr, Source sourcePtr, TextWriter data)274			{275				data.WriteLine ("{0}cpobj {1} {2} {3}", this.prefix, this.meta_data_provider.FullName (type), SourceName (destPtr), SourceName (sourcePtr));276				return Dummy.Value;277			}278			public Dummy Initobj (Label pc, TypeNode type, Source ptr, TextWriter data)279			{280				data.WriteLine ("{0}initobj {1} {2}", this.prefix, this.meta_data_provider.FullName (type), SourceName (ptr));281				return Dummy.Value;282			}283			public Dummy LoadElement (Label pc, TypeNode type, Dest dest, Source array, Source index, TextWriter data)284			{285				data.WriteLine ("{0}{2} = ldelem {1} {3}[{4}]", this.prefix, this.meta_data_provider.FullName (type), DestName (dest), SourceName (array), SourceName (index));286				return Dummy.Value;287			}288			public Dummy LoadField (Label pc, Field field, Dest dest, Source obj, TextWriter data)289			{290				data.WriteLine ("{0}{2} = ldfld {1} {3}", this.prefix, this.meta_data_provider.Name (field), DestName (dest), SourceName (obj));291				return Dummy.Value;292			}293			public Dummy LoadFieldAddress (Label pc, Field field, Dest dest, Source obj, TextWriter data)294			{295				data.WriteLine ("{0}{2} = ldflda {1} {3}", this.prefix, this.meta_data_provider.Name (field), DestName (dest), SourceName (obj));296				return Dummy.Value;297			}298			public Dummy LoadLength (Label pc, Dest dest, Source array, TextWriter data)299			{300				data.WriteLine ("{0}{1} = ldlen {2}", this.prefix, DestName (dest), SourceName (array));301				return Dummy.Value;302			}303			public Dummy LoadStaticField (Label pc, Field field, Dest dest, TextWriter data)304			{305				data.WriteLine ("{0}{2} = ldsfld {1}", this.prefix, this.meta_data_provider.Name (field), DestName (dest));306				return Dummy.Value;307			}308			public Dummy LoadStaticFieldAddress (Label pc, Field field, Dest dest, TextWriter data)309			{310				data.WriteLine ("{0}{2} = ldsflda {1}", this.prefix, this.meta_data_provider.Name (field), DestName (dest));311				return Dummy.Value;312			}313			public Dummy LoadTypeToken (Label pc, TypeNode type, Dest dest, TextWriter data)314			{315				throw new NotImplementedException ();316			}317			public Dummy LoadFieldToken (Label pc, Field type, Dest dest, TextWriter data)318			{319				throw new NotImplementedException ();320			}321			public Dummy LoadMethodToken (Label pc, Method type, Dest dest, TextWriter data)322			{323				throw new NotImplementedException ();324			}325			public Dummy NewArray<ArgList> (Label pc, TypeNode type, Dest dest, ArgList lengths, TextWriter data) where ArgList : IIndexable<Source>326			{327				throw new NotImplementedException ();328			}329			public Dummy NewObj<ArgList> (Label pc, Method ctor, Dest dest, ArgList args, TextWriter data) where ArgList : IIndexable<Source>330			{331				data.Write ("{0}{2} = newobj {1}(", this.prefix, this.meta_data_provider.FullName (ctor), DestName (dest));332				if (args != null) {333					for (int i = 0; i < args.Count; ++i)334						data.Write ("{0} ", SourceName (args [i]));335				}336				data.WriteLine (")");337				return Dummy.Value;338			}339			public Dummy MkRefAny (Label pc, TypeNode type, Dest dest, Source obj, TextWriter data)340			{341				throw new NotImplementedException ();342			}343			public Dummy RefAnyType (Label pc, Dest dest, Source source, TextWriter data)344			{345				throw new NotImplementedException ();346			}347			public Dummy RefAnyVal (Label pc, TypeNode type, Dest dest, Source source, TextWriter data)348			{349				throw new NotImplementedException ();350			}351			public Dummy Rethrow (Label pc, TextWriter data)352			{353				throw new NotImplementedException ();354			}355			public Dummy StoreElement (Label pc, TypeNode type, Source array, Source index, Source value, TextWriter data)356			{357				throw new NotImplementedException ();358			}359			public Dummy StoreField (Label pc, Field field, Source obj, Source value, TextWriter data)360			{361				data.WriteLine ("{0}stfld {1} {2} {3}", this.prefix, this.meta_data_provider.Name (field), SourceName (obj), SourceName (value));362				return Dummy.Value;363			}364			public Dummy StoreStaticField (Label pc, Field field, Source value, TextWriter data)365			{366				data.WriteLine ("{0}stsfld {1} {2}", this.prefix, this.meta_data_provider.Name (field), SourceName (value));367				return Dummy.Value;368			}369			public Dummy Throw (Label pc, Source exception, TextWriter data)370			{371				throw new NotImplementedException ();372			}373			public Dummy Unbox (Label pc, TypeNode type, Dest dest, Source obj, TextWriter data)374			{375				throw new NotImplementedException ();376			}377			public Dummy UnboxAny (Label pc, TypeNode type, Dest dest, Source obj, TextWriter data)378			{379				throw new NotImplementedException ();380			}381			#endregion382			public void PrintCodeAt (Label label, string prefix, TextWriter tw)383			{384				this.prefix = prefix;385				this.il_decoder.ForwardDecode<TextWriter, Dummy, Printer<Label, Source, Dest, Context, EdgeData>> (label, this, tw);386			}387			private string SourceName (Source src)388			{389				return this.source_to_string != null ? this.source_to_string (src) : null;390			}391			private string DestName (Dest dest)392			{393				return this.dest_to_string != null ? this.dest_to_string (dest) : null;394			}395		}396		#endregion397	}398}...

Full Screen

Full Screen

CodeProviderImpl.cs

Source:CodeProviderImpl.cs Github

copy

Full Screen

...52			case NodeType.Nop:53				return visitor.Nop (pc, data);54			case NodeType.Clt:55			case NodeType.Lt:56				return visitor.Binary (pc, BinaryOperator.Clt, Dummy.Value, Dummy.Value, Dummy.Value, data);57			case NodeType.Cgt:58			case NodeType.Gt:59				return visitor.Binary (pc, BinaryOperator.Cgt, Dummy.Value, Dummy.Value, Dummy.Value, data);60			case NodeType.Ceq:61			case NodeType.Eq:62				return visitor.Binary (pc, BinaryOperator.Ceq, Dummy.Value, Dummy.Value, Dummy.Value, data);63			case NodeType.Ne:64				return visitor.Binary (pc, BinaryOperator.Cne_Un, Dummy.Value, Dummy.Value, Dummy.Value, data);65			case NodeType.Ge:66				return visitor.Binary (pc, BinaryOperator.Cge, Dummy.Value, Dummy.Value, Dummy.Value, data);67			case NodeType.Le:68				return visitor.Binary (pc, BinaryOperator.Cle, Dummy.Value, Dummy.Value, Dummy.Value, data);69			case NodeType.Add:70				return visitor.Binary (pc, BinaryOperator.Add, Dummy.Value, Dummy.Value, Dummy.Value, data);71			case NodeType.Sub:72				return visitor.Binary (pc, BinaryOperator.Sub, Dummy.Value, Dummy.Value, Dummy.Value, data);73			case NodeType.Rem:74				return visitor.Binary (pc, BinaryOperator.Rem, Dummy.Value, Dummy.Value, Dummy.Value, data);75			case NodeType.Rem_Un:76				return visitor.Binary (pc, BinaryOperator.Rem_Un, Dummy.Value, Dummy.Value, Dummy.Value, data);77			case NodeType.Mul:78				return visitor.Binary (pc, BinaryOperator.Mul, Dummy.Value, Dummy.Value, Dummy.Value, data);79			case NodeType.Div:80				return visitor.Binary (pc, BinaryOperator.Div, Dummy.Value, Dummy.Value, Dummy.Value, data);81			case NodeType.Div_Un:82				return visitor.Binary (pc, BinaryOperator.Div_Un, Dummy.Value, Dummy.Value, Dummy.Value, data);83			case NodeType.And:84				return visitor.Binary (pc, BinaryOperator.And, Dummy.Value, Dummy.Value, Dummy.Value, data);85			case NodeType.Or:86				return visitor.Binary (pc, BinaryOperator.Or, Dummy.Value, Dummy.Value, Dummy.Value, data);87			case NodeType.Shr:88				return visitor.Binary (pc, BinaryOperator.Shr, Dummy.Value, Dummy.Value, Dummy.Value, data);89			case NodeType.Xor:90				return visitor.Binary (pc, BinaryOperator.Xor, Dummy.Value, Dummy.Value, Dummy.Value, data);91			case NodeType.Shl:92				return visitor.Binary (pc, BinaryOperator.Shl, Dummy.Value, Dummy.Value, Dummy.Value, data);93			case NodeType.Shr_Un:94				return visitor.Binary (pc, BinaryOperator.Shr_Un, Dummy.Value, Dummy.Value, Dummy.Value, data);95			case NodeType.Literal:96				var literal = (Literal) node;97				if (literal.Value == null)98					return visitor.LoadNull (pc, Dummy.Value, data);99				if (literal.Type == CoreSystemTypes.Instance.TypeBoolean && (bool) literal.Value)100					return visitor.LoadConst (pc, CoreSystemTypes.Instance.TypeInt32, 1, Dummy.Value, data);101				return visitor.LoadConst (pc, literal.Type, literal.Value, Dummy.Value, data);102			case NodeType.This:103			case NodeType.Parameter:104				return visitor.LoadArg (pc, (Parameter) node, false, Dummy.Value, data);105			case NodeType.Local:106				return visitor.LoadLocal (pc, (Local) node, Dummy.Value, data);107			case NodeType.Branch:108				var branch = (Branch) node;109				if (branch.Condition != null)110					return visitor.BranchTrue (pc, new PC (branch.Target), Dummy.Value, data);111				return visitor.Branch (pc, new PC (branch.Target), branch.LeavesExceptionBlock, data);112			case NodeType.ExpressionStatement:113				break;114			case NodeType.Box:115				break;116			case NodeType.Return:117				return visitor.Return (pc, Dummy.Value, data);118			case NodeType.Neg:119				return visitor.Unary (pc, UnaryOperator.Neg, false, Dummy.Value, Dummy.Value, data);120			case NodeType.Not:121			case NodeType.LogicalNot:122				return visitor.Unary (pc, UnaryOperator.Not, false, Dummy.Value, Dummy.Value, data);123			case NodeType.Conv:124				break;125			case NodeType.Conv_I1:126				return visitor.Unary (pc, UnaryOperator.Conv_i1, false, Dummy.Value, Dummy.Value, data);127			case NodeType.Conv_I2:128				return visitor.Unary (pc, UnaryOperator.Conv_i2, false, Dummy.Value, Dummy.Value, data);129			case NodeType.Conv_I4:130				return visitor.Unary (pc, UnaryOperator.Conv_i4, false, Dummy.Value, Dummy.Value, data);131			case NodeType.Conv_I8:132				return visitor.Unary (pc, UnaryOperator.Conv_i8, false, Dummy.Value, Dummy.Value, data);133			case NodeType.Conv_R4:134				return visitor.Unary (pc, UnaryOperator.Conv_r4, false, Dummy.Value, Dummy.Value, data);135			case NodeType.Conv_R8:136				return visitor.Unary (pc, UnaryOperator.Conv_r8, false, Dummy.Value, Dummy.Value, data);137			case NodeType.MethodContract:138				return visitor.Nop (pc, data);139			case NodeType.Requires:140				return visitor.Assume (pc, EdgeTag.Requires, Dummy.Value, data);141			case NodeType.Call:142				var call = (MethodCall) node;143				Method method = GetMethodFrom (call.Callee);144				if (method.HasGenericParameters)145					throw new NotImplementedException ();146				if (method.Name != null && method.DeclaringType.Name != null && method.DeclaringType.Name.EndsWith ("Contract")) {147					switch (method.Name) {148					case "Assume":149						if (method.Parameters.Count == 1)150							return visitor.Assume (pc, EdgeTag.Assume, Dummy.Value, data);151						break;152					case "Assert":153						if (method.Parameters.Count == 1)154							return visitor.Assert (pc, EdgeTag.Assert, Dummy.Value, data);155						break;156					}157				}158				Indexable<Dummy> parameters = DummyIndexable (method);159				return visitor.Call (pc, method, false, GetVarargs (call, method), Dummy.Value, parameters, data);160			case NodeType.AssignmentStatement:161				var assign = ((AssignmentStatement) node);162				var local = assign.Target as Local;163				if (local != null)164					return visitor.StoreLocal (pc, local, Dummy.Value, data);165				var parameter = assign.Target as Parameter;166				if (parameter != null)167					return visitor.StoreArg (pc, parameter, Dummy.Value, data);168				var binding = assign.Target as MemberBinding;169				if (binding != null) {170					if (binding.BoundMember.IsStatic)171						return visitor.StoreStaticField (pc, (Field) binding.BoundMember, Dummy.Value, data);172					else173						return visitor.StoreField (pc, (Field) binding.BoundMember, Dummy.Value, Dummy.Value, data);174				}175				throw new NotImplementedException ();176			case NodeType.Construct:177				Method ctor = GetMethodFrom (((Construct) node).Constructor);178				if (!(ctor.DeclaringType is ArrayTypeNode))179					return visitor.NewObj (pc, ctor, Dummy.Value, DummyIndexable (ctor), data);180				var arrayType = (ArrayTypeNode) ctor.DeclaringType;181				return visitor.NewArray (pc, arrayType, Dummy.Value, DummyIndexable (ctor), data);182			default:183				return visitor.Nop (pc, data);184			}185			throw new NotImplementedException ();186		}187		public bool Next (PC pc, out PC nextLabel)188		{189			Node nested;190			if (Decode (pc, out nested) == null && pc.Node != null) {191				nextLabel = new PC (pc.Node, pc.Index + 1);192				return true;193			}194			nextLabel = new PC ();195			return false;196		}197		public int GetILOffset (PC current)198		{199			throw new NotImplementedException ();200		}201		#endregion202		private static Indexable<Dummy> DummyIndexable (Method method)203		{204			return new Indexable<Dummy> (Enumerable.Range (0, method.Parameters.Count).Select (it => Dummy.Value).ToList ());205		}206		private static Indexable<TypeNode> GetVarargs (MethodCall call, Method method)207		{208			int methodCount = method.Parameters.Count;209			int callCount = call.Arguments.Count;210			if (callCount <= methodCount)211				return new Indexable<TypeNode> (null);212			var array = new TypeNode[callCount - methodCount];213			for (int i = methodCount; i < callCount; i++)214				array [i - methodCount] = call.Arguments [i - methodCount].Type;215			return new Indexable<TypeNode> (array);216		}217		private Method GetMethodFrom (Expression callee)218		{219			return (Method) ((MemberBinding) callee).BoundMember;220		}221		private static bool IsAtomicNested (Node nested)222		{223			if (nested == null)224				return false;225			switch (nested.NodeType) {226			case NodeType.Local:227			case NodeType.Parameter:228			case NodeType.Literal:229			case NodeType.This:230				return true;231			default:232				return false;233			}234		}235		private Node Decode (PC pc, out Node nested)236		{237			Node node = DecodeInflate (pc, out nested);238			return node;239		}240		/// <summary>241		/// Decodes pc242		/// </summary>243		/// <param name="pc"></param>244		/// <param name="nested"></param>245		/// <returns>If node has nested, returns null and (nested = child). If last child given, node equals pc.Node</returns>246		private static Node DecodeInflate (PC pc, out Node nested)247		{248			Node node = pc.Node;249			if (node == null) {250				nested = null;251				return null;252			}253			int index = pc.Index;254			switch (node.NodeType) {255			case NodeType.MethodContract:256				var methodContract = (MethodContract) node;257				if (index < methodContract.RequiresCount) {258					nested = methodContract.Requires [index];259					return null;260				}261				if (index == methodContract.RequiresCount) {262					nested = null;263					return methodContract;264				}265				//todo: aggregate ensures266				nested = null;267				return methodContract;268			case NodeType.Requires:269				var requires = (Requires) node;270				if (index == 0) {271					nested = requires.Assertion;272					return null;273				}274				nested = null;275				return requires;276			case NodeType.Block:277				var block = (Block) node;278				if (block.Statements == null) {279					nested = null;280					return block;281				}282				nested = index >= block.Statements.Count ? null : block.Statements [index];283				return index + 1 < block.Statements.Count ? null : block;284			case NodeType.Return:285				var ret = (Return) node;286				if (ret.Expression != null && index == 0) {287					nested = ret.Expression;288					return null;289				}290				nested = null;291				return ret;292			case NodeType.AssignmentStatement:293				var assign = (AssignmentStatement) node;294				int innerIndex = index;295				{296					var bind = assign.Target as MemberBinding;297					if (bind != null) {298						++innerIndex;299						if (bind.BoundMember.IsStatic)300							++innerIndex;301						if (innerIndex == 1) {302							nested = bind.TargetObject;303							return null;304						}305					} else if (assign.Target is Variable)306						innerIndex += 2;307					else {308						nested = null;309						return assign;310					}311				}312				if (innerIndex == 2) {313					nested = assign.Source;314					return null;315				}316				nested = null;317				return assign;318			case NodeType.ExpressionStatement:319				var expressionStatement = (ExpressionStatement) node;320				nested = expressionStatement.Expression;321				return expressionStatement;322			case NodeType.MethodCall:323			case NodeType.Call:324			case NodeType.Calli:325			case NodeType.CallVirt:326				var methodCall = (MethodCall) node;327				var binding = (MemberBinding) methodCall.Callee;328				if (binding.BoundMember.IsStatic) {329					if (index < methodCall.Arguments.Count) {330						nested = methodCall.Arguments [index];331						return null;332					}333					nested = null;334					return methodCall;335				}336				if (index == 0) {337					nested = binding.TargetObject;338					return null;339				}340				if (index < methodCall.Arguments.Count + 1) {341					nested = methodCall.Arguments [index - 1];342					return null;343				}344				nested = null;345				return methodCall;346			case NodeType.MemberBinding:347				var bind1 = ((MemberBinding) node);348				if (index == 0 && !bind1.BoundMember.IsStatic) {349					nested = bind1.TargetObject;350					return null;351				}352				nested = null;353				return bind1;354			case NodeType.Construct:355				var construct = (Construct) node;356				if (index < construct.Arguments.Count) {357					nested = construct.Arguments [index];358					return null;359				}360				nested = null;361				return construct;362			case NodeType.Branch:363				var branch = ((Branch) node);364				if (branch.Condition != null && index == 0) {365					nested = branch.Condition;366					return null;367				}368				nested = null;369				return branch;370			default:371				var binary = node as BinaryExpression;372				if (binary != null) {373					if (index == 0) {374						nested = binary.Left;375						return null;376					}377					if (index == 1) {378						nested = binary.Right;379						return null;380					}381					nested = null;382					return binary;383				}384				var unary = node as UnaryExpression;385				if (unary != null) {386					if (index == 0) {387						nested = unary.Operand;388						return null;389					}390					nested = null;391					return unary;392				}393				//todo: ternary394				nested = null;395				return node;396			}397		}398		public PC Entry (Method method)399		{400			return new PC (method.Body);401		}402		#region Implementation of IMethodCodeProvider<PC,Local,Parameter,Method,FieldReference,TypeReference,Dummy>403		public bool IsFaultHandler (ExceptionHandler handler)404		{405			return handler.HandlerType == NodeType.FaultHandler;406		}407		public bool IsFilterHandler (ExceptionHandler handler)408		{409			return handler.HandlerType == NodeType.Filter;410		}411		public bool IsFinallyHandler (ExceptionHandler handler)412		{413			return handler.HandlerType == NodeType.Finally;414		}415		public PC FilterExpressionStart (ExceptionHandler handler)416		{...

Full Screen

Full Screen

SettingsTests.cs

Source:SettingsTests.cs Github

copy

Full Screen

...35			if (File.Exists(projectSettingsPath))36				File.Delete(projectSettingsPath);37		}38		[Serializable]39		struct DummyStruct : IEquatable<DummyStruct>40		{41			public string stringValue;42			public int intValue;43			public DummyStruct(string s, int i)44			{45				stringValue = s;46				intValue = i;47			}48			public static DummyStruct defaultValue49			{50				get { return new DummyStruct("I'm a string!", 42); }51			}52			public bool Equals(DummyStruct other)53			{54				return string.Equals(stringValue, other.stringValue) && intValue == other.intValue;55			}56			public override bool Equals(object obj)57			{58				if (ReferenceEquals(null, obj))59					return false;60				return obj is DummyStruct && Equals((DummyStruct)obj);61			}62			public override int GetHashCode()63			{64				unchecked65				{66					return ((stringValue != null ? stringValue.GetHashCode() : 0) * 397) ^ intValue;67				}68			}69			public static bool operator ==(DummyStruct left, DummyStruct right)70			{71				return left.Equals(right);72			}73			public static bool operator !=(DummyStruct left, DummyStruct right)74			{75				return !left.Equals(right);76			}77			public override string ToString()78			{79				return stringValue + "  " + intValue;80			}81		}82		[Serializable]83		class DummyClass : IEquatable<DummyClass>84		{85			public string stringValue;86			public int intValue;87			public DummyClass(string s, int i)88			{89				stringValue = s;90				intValue = i;91			}92			public static DummyClass defaultValue93			{94				get { return new DummyClass("I'm a string!", 42); }95			}96			public bool Equals(DummyClass other)97			{98				return string.Equals(stringValue, other.stringValue) && intValue == other.intValue;99			}100			public override bool Equals(object obj)101			{102				if (ReferenceEquals(null, obj))103					return false;104				return obj is DummyClass && Equals((DummyClass)obj);105			}106			public override int GetHashCode()107			{108				unchecked109				{110					return ((stringValue != null ? stringValue.GetHashCode() : 0) * 397) ^ intValue;111				}112			}113			public static bool operator ==(DummyClass left, DummyClass right)114			{115				return left.Equals(right);116			}117			public static bool operator !=(DummyClass left, DummyClass right)118			{119				return !left.Equals(right);120			}121			public override string ToString()122			{123				return stringValue + "  " + intValue;124			}125		}126		static UserSetting<bool> s_StaticBoolUser = new UserSetting<bool>(settings, "tests.user.static.bool", true, SettingsScope.User);127		static UserSetting<bool> s_StaticBoolProject = new UserSetting<bool>(settings, "tests.project.static.bool", true, SettingsScope.Project);128		static UserSetting<string> s_StaticStringUser = new UserSetting<string>(settings, "tests.user.static.string", "Hello, world!", SettingsScope.User);129		static UserSetting<string> s_StaticStringProject = new UserSetting<string>(settings, "tests.project.static.string", "Goodbye, world!", SettingsScope.Project);130		static UserSetting<DummyStruct> s_StaticStructUser = new UserSetting<DummyStruct>(settings, "tests.user.static.struct", DummyStruct.defaultValue, SettingsScope.User);131		static UserSetting<DummyStruct> s_StaticStructProject = new UserSetting<DummyStruct>(settings, "tests.project.static.struct", DummyStruct.defaultValue, SettingsScope.Project);132		static UserSetting<DummyClass> s_StaticClassUser = new UserSetting<DummyClass>(settings, "tests.user.static.class", DummyClass.defaultValue, SettingsScope.User);133		static UserSetting<DummyClass> s_StaticClassProject = new UserSetting<DummyClass>(settings, "tests.project.static.class", DummyClass.defaultValue, SettingsScope.Project);134		static IUserSetting[] s_AllPreferences = new IUserSetting[]135		{136			s_StaticBoolUser,137			s_StaticBoolProject,138			s_StaticStringUser,139			s_StaticStringProject,140			s_StaticStructUser,141			s_StaticStructProject,142			s_StaticClassUser,143			s_StaticClassProject144		};145		[Test]146		public static void DefaultsAreCorrect()147		{148			try149			{150				foreach (var pref in s_AllPreferences)151					pref.Reset();152				Assert.IsTrue((bool)s_StaticBoolUser, s_StaticBoolUser.ToString());153				Assert.IsTrue((bool)s_StaticBoolProject, s_StaticBoolProject.ToString());154				Assert.AreEqual("Hello, world!", (string)s_StaticStringUser, s_StaticStringUser.ToString());155				Assert.AreEqual("Goodbye, world!", (string)s_StaticStringProject, s_StaticStringProject.ToString());156				Assert.AreEqual(DummyStruct.defaultValue, (DummyStruct)s_StaticStructUser, s_StaticStructUser.ToString());157				Assert.AreEqual(DummyStruct.defaultValue, (DummyStruct)s_StaticStructProject, s_StaticStructProject.ToString());158				Assert.AreEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassUser, s_StaticClassUser.ToString());159				Assert.AreEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassProject, s_StaticClassProject.ToString());160			}161			catch (Exception e)162			{163				Debug.LogError(e.ToString());164			}165		}166		[Test]167		public static void SetValue()168		{169			try170			{171				// BOOl172				s_StaticBoolUser.value = false;173				s_StaticBoolProject.value = false;174				Assert.IsFalse((bool)s_StaticBoolUser);175				Assert.IsFalse((bool)s_StaticBoolProject);176				// STRING177				s_StaticStringUser.value = "Some more text";178				s_StaticStringProject.value = "Some text here";179				Assert.AreEqual("Some more text", (string)s_StaticStringUser);180				Assert.AreEqual("Some text here", (string)s_StaticStringProject);181				// STRUCT182				var userStruct = new DummyStruct("Changed text", 23);183				var projectStruct = new DummyStruct("Slightly different text", -9825);184				s_StaticStructUser.SetValue(userStruct);185				s_StaticStructProject.SetValue(projectStruct);186				Assert.AreEqual(userStruct, (DummyStruct)s_StaticStructUser);187				Assert.AreEqual(projectStruct, (DummyStruct)s_StaticStructProject);188				// CLASS189				var userClass = new DummyClass("Changed text", 23);190				var projectClass = new DummyClass("Slightly different text", -9825);191				s_StaticClassUser.SetValue(userClass);192				s_StaticClassProject.SetValue(projectClass);193				Assert.AreEqual(userClass, (DummyClass)s_StaticClassUser);194				Assert.AreEqual(projectClass, (DummyClass)s_StaticClassProject);195			}196			catch (Exception e)197			{198				Debug.LogError(e.ToString());199			}200		}201		[Test]202		public static void SetAndReset()203		{204			try205			{206				// BOOL207				s_StaticBoolUser.value = false;208				s_StaticBoolProject.value = false;209				// STRING210				s_StaticStringUser.value = "Some more text";211				s_StaticStringProject.value = "Some text here";212				// STRUCT213				s_StaticStructUser.SetValue(new DummyStruct("Changed text", 23));214				s_StaticStructProject.SetValue(new DummyStruct("Slightly different text", -9825));215				// CLASS216				s_StaticClassUser.SetValue(new DummyClass("Changed text", 23));217				s_StaticClassProject.SetValue(new DummyClass("Slightly different text", -9825));218				Assert.IsFalse((bool)s_StaticBoolUser);219				Assert.IsFalse((bool)s_StaticBoolProject);220				Assert.AreNotEqual("Hello, world!", (string)s_StaticStringUser);221				Assert.AreNotEqual("Goodbye, world!", (string)s_StaticStringProject);222				Assert.AreNotEqual(DummyStruct.defaultValue, (DummyStruct)s_StaticStructUser);223				Assert.AreNotEqual(DummyStruct.defaultValue, (DummyStruct)s_StaticStructProject);224				Assert.AreNotEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassUser);225				Assert.AreNotEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassProject);226				foreach (var pref in s_AllPreferences)227					pref.Reset();228				Assert.IsTrue((bool)s_StaticBoolUser);229				Assert.IsTrue((bool)s_StaticBoolProject);230				Assert.AreEqual("Hello, world!", (string)s_StaticStringUser);231				Assert.AreEqual("Goodbye, world!", (string)s_StaticStringProject);232				Assert.AreEqual(DummyStruct.defaultValue, (DummyStruct)s_StaticStructUser);233				Assert.AreEqual(DummyStruct.defaultValue, (DummyStruct)s_StaticStructProject);234				Assert.AreEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassUser);235				Assert.AreEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassProject);236			}237			catch (Exception e)238			{239				Debug.LogError(e.ToString());240			}241		}242		[Test]243		public static void SerializeAndLoad()244		{245			try246			{247				foreach (var pref in s_AllPreferences)248					pref.Reset();249				settings.Save();250				var instance = new Settings(k_PackageName);251				Assert.AreEqual((bool)s_StaticBoolUser, instance.Get<bool>(s_StaticBoolUser.key, s_StaticBoolUser.scope));252				Assert.AreEqual((bool)s_StaticBoolProject, instance.Get<bool>(s_StaticBoolProject.key, s_StaticBoolProject.scope));253				Assert.AreEqual((string)s_StaticStringUser, instance.Get<string>(s_StaticStringUser.key, s_StaticStringUser.scope));254				Assert.AreEqual((string)s_StaticStringProject, instance.Get<string>(s_StaticStringProject.key, s_StaticStringProject.scope));255				Assert.AreEqual((DummyStruct)s_StaticStructUser, instance.Get<DummyStruct>(s_StaticStructUser.key, s_StaticStructUser.scope));256				Assert.AreEqual((DummyStruct)s_StaticStructProject, instance.Get<DummyStruct>(s_StaticStructProject.key, s_StaticStructProject.scope));257				Assert.AreEqual((DummyClass)s_StaticClassUser, instance.Get<DummyClass>(s_StaticClassUser.key, s_StaticClassUser.scope));258				Assert.AreEqual((DummyClass)s_StaticClassProject, instance.Get<DummyClass>(s_StaticClassProject.key, s_StaticClassProject.scope));259			}260			catch (Exception e)261			{262				Debug.LogError(e.ToString());263			}264		}265		[Test]266		public static void DeleteKeys()267		{268			try269			{270				foreach (var pref in s_AllPreferences)271					pref.Delete();272				settings.Save();273				var instance = new Settings(k_PackageName);274				Assert.IsFalse(instance.ContainsKey<bool>("tests.user.static.bool", SettingsScope.User), "tests.user.static.bool");275				Assert.IsFalse(instance.ContainsKey<bool>("tests.project.static.bool", SettingsScope.Project), "tests.project.static.bool");276				Assert.IsFalse(instance.ContainsKey<string>("tests.user.static.string", SettingsScope.User), "tests.user.static.string");277				Assert.IsFalse(instance.ContainsKey<string>("tests.project.static.string", SettingsScope.Project), "tests.project.static.string");278				Assert.IsFalse(instance.ContainsKey<DummyStruct>("tests.user.static.struct", SettingsScope.User), "tests.user.static.struct");279				Assert.IsFalse(instance.ContainsKey<DummyStruct>("tests.project.static.struct", SettingsScope.Project), "tests.project.static.struct");280				Assert.IsFalse(instance.ContainsKey<DummyClass>("tests.user.static.class", SettingsScope.User), "tests.user.static.class");281				Assert.IsFalse(instance.ContainsKey<DummyClass>("tests.project.static.class", SettingsScope.Project), "tests.project.static.class");282			}283			catch (Exception e)284			{285				Debug.LogError(e.ToString());286			}287		}288		[Test]289		public static void KeysExistInSettingsInstance()290		{291			try292			{293				foreach (var pref in s_AllPreferences)294					pref.Reset();295				settings.Save();296				Assert.IsTrue(settings.ContainsKey<bool>("tests.user.static.bool", SettingsScope.User), "tests.user.static.bool");297				Assert.IsTrue(settings.ContainsKey<bool>("tests.project.static.bool", SettingsScope.Project), "tests.project.static.bool");298				Assert.IsTrue(settings.ContainsKey<string>("tests.user.static.string", SettingsScope.User), "tests.user.static.string");299				Assert.IsTrue(settings.ContainsKey<string>("tests.project.static.string", SettingsScope.Project), "tests.project.static.string");300				Assert.IsTrue(settings.ContainsKey<DummyStruct>("tests.user.static.struct", SettingsScope.User), "tests.user.static.struct");301				Assert.IsTrue(settings.ContainsKey<DummyStruct>("tests.project.static.struct", SettingsScope.Project), "tests.project.static.struct");302				Assert.IsTrue(settings.ContainsKey<DummyClass>("tests.user.static.class", SettingsScope.User), "tests.user.static.class");303				Assert.IsTrue(settings.ContainsKey<DummyClass>("tests.project.static.class", SettingsScope.Project), "tests.project.static.class");304			}305			catch (Exception e)306			{307				Debug.LogError(e.ToString());308			}309		}310		[Test]311		public static void KeysExistInSerializedForm()312		{313			try314			{315				foreach (var pref in s_AllPreferences)316					pref.Reset();317				settings.Save();318				var instance = new Settings(k_PackageName);319				Assert.IsTrue(instance.ContainsKey<bool>("tests.user.static.bool", SettingsScope.User), "tests.user.static.bool");320				Assert.IsTrue(instance.ContainsKey<bool>("tests.project.static.bool", SettingsScope.Project), "tests.project.static.bool");321				Assert.IsTrue(instance.ContainsKey<string>("tests.user.static.string", SettingsScope.User), "tests.user.static.string");322				Assert.IsTrue(instance.ContainsKey<string>("tests.project.static.string", SettingsScope.Project), "tests.project.static.string");323				Assert.IsTrue(instance.ContainsKey<DummyStruct>("tests.user.static.struct", SettingsScope.User), "tests.user.static.struct");324				Assert.IsTrue(instance.ContainsKey<DummyStruct>("tests.project.static.struct", SettingsScope.Project), "tests.project.static.struct");325				Assert.IsTrue(instance.ContainsKey<DummyClass>("tests.user.static.class", SettingsScope.User), "tests.user.static.class");326				Assert.IsTrue(instance.ContainsKey<DummyClass>("tests.project.static.class", SettingsScope.Project), "tests.project.static.class");327			}328			catch (Exception e)329			{330				Debug.LogError(e.ToString());331			}332		}333		[Test]334		public static void ChangingClassValuesSaves()335		{336			try337			{338				s_StaticClassUser.Reset();339				s_StaticClassProject.Reset();340				Assert.AreEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassUser);341				Assert.AreEqual(DummyClass.defaultValue, (DummyClass)s_StaticClassProject);342				var userReference = s_StaticClassUser.value;343				var projectReference = s_StaticClassProject.value;344				userReference.intValue = 200;345				projectReference.intValue = 200;346				s_StaticClassProject.ApplyModifiedProperties();347				s_StaticClassUser.ApplyModifiedProperties();348				Assert.IsTrue(ReferenceEquals(s_StaticClassProject.value, projectReference));349				Assert.IsTrue(ReferenceEquals(s_StaticClassUser.value, userReference));350				Assert.AreEqual(200, s_StaticClassUser.value.intValue, "After ApplyModifiedProperties");351				Assert.AreEqual(200, s_StaticClassProject.value.intValue, "After ApplyModifiedProperties");352				settings.Save();353				var instance = new Settings(k_PackageName);354				Assert.AreEqual(200, instance.Get<DummyClass>(s_StaticClassUser.key, s_StaticClassUser.scope).intValue, "Reload Settings Instance");355				Assert.AreEqual(200, instance.Get<DummyClass>(s_StaticClassProject.key, s_StaticClassProject.scope).intValue, "Reload Settings Instance");356			}357			catch (Exception e)358			{359				Debug.LogError(e.ToString());360			}361		}362	}363}...

Full Screen

Full Screen

DevDiv_374539.cs

Source:DevDiv_374539.cs Github

copy

Full Screen

...179    private static void D10()180    {181    }182    [MethodImplAttribute(MethodImplOptions.NoInlining)]183    private static void Dummy()184    {185    }186    [MethodImplAttribute(MethodImplOptions.NoInlining)]187    private static void GenericRecursion<T, U>(int level)188    {189        if (level == 0) return;190        level--;191        GenericRecursion<KeyValuePair<T, U>, U>(level);192        GenericRecursion<KeyValuePair<U, T>, U>(level);193        GenericRecursion<T, KeyValuePair<T, U>>(level);194        GenericRecursion<T, KeyValuePair<U, T>>(level);195        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();196        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();197        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();198        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();199        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();200        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();201        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();202        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();203        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();204        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();205        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();206        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();207        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();208        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();209        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();210        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();211        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();212        Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy(); Dummy();213    }214    private static int Main()215    {216        try217        {218            Console.WriteLine("Eating address space");219            EatAddressSpace();220            Console.WriteLine("Eating code heap");221            GenericRecursion<int, uint>(5);222            A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10();223            B1(); B2(); B3(); B4(); B5(); B6(); B7(); B8(); B9(); B10();224            C1(); C2(); C3(); C4(); C5(); C6(); C7(); C8(); C9(); C10();225            D1(); D2(); D3(); D4(); D5(); D6(); D7(); D8(); D9(); D10();226            A1(); A2(); A3(); A4(); A5(); A6(); A7(); A8(); A9(); A10();...

Full Screen

Full Screen

DummyClient.cs

Source:DummyClient.cs Github

copy

Full Screen

...16using GoogleMobileAds.Api;17using UnityEngine;18namespace GoogleMobileAds.Common19{20    public class DummyClient : IBannerClient, IInterstitialClient, IRewardBasedVideoAdClient,21            IAdLoaderClient, INativeExpressAdClient, IMobileAdsClient22    {23        public DummyClient()24        {25            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);26        }27        // Disable warnings for unused dummy ad events.28        #pragma warning disable 6729        public event EventHandler<EventArgs> OnAdLoaded;30        public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;31        public event EventHandler<EventArgs> OnAdOpening;32        public event EventHandler<EventArgs> OnAdStarted;33        public event EventHandler<EventArgs> OnAdClosed;34        public event EventHandler<Reward> OnAdRewarded;35        public event EventHandler<EventArgs> OnAdLeavingApplication;36        public event EventHandler<CustomNativeEventArgs> OnCustomNativeTemplateAdLoaded;37        #pragma warning restore 6738        public string UserId39        {40            get41            {42                Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);43                return "UserId";44            }45            set46            {47                Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);48            }49        }50        public void Initialize(string appId)51        {52            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);53        }54        public void SetApplicationMuted(bool muted)55        {56            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);57        }58        public void SetApplicationVolume(float volume)59        {60            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);61        }62        public void CreateBannerView(string adUnitId, AdSize adSize, AdPosition position)63        {64            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);65        }66        public void CreateBannerView(string adUnitId, AdSize adSize, int positionX, int positionY)67        {68            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);69        }70        public void LoadAd(AdRequest request)71        {72            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);73        }74        public void ShowBannerView()75        {76            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);77        }78        public void HideBannerView()79        {80            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);81        }82        public void DestroyBannerView()83        {84            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);85        }86        public void CreateInterstitialAd(string adUnitId)87        {88            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);89        }90        public bool IsLoaded()91        {92            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);93            return true;94        }95        public void ShowInterstitial()96        {97            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);98        }99        public void DestroyInterstitial()100        {101            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);102        }103        public void CreateRewardBasedVideoAd()104        {105            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);106        }107        public void SetUserId(string userId)108        {109            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);110        }111        public void LoadAd(AdRequest request, string adUnitId)112        {113            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);114        }115        public void DestroyRewardBasedVideoAd()116        {117            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);118        }119        public void ShowRewardBasedVideoAd()120        {121            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);122        }123        public void CreateAdLoader(AdLoader.Builder builder)124        {125            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);126        }127        public void Load(AdRequest request)128        {129            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);130        }131        public void CreateNativeExpressAdView(string adUnitId, AdSize adSize, AdPosition position)132        {133            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);134        }135        public void CreateNativeExpressAdView(string adUnitId, AdSize adSize, int positionX, int positionY)136        {137            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);138        }139        public void SetAdSize(AdSize adSize)140        {141            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);142        }143        public void ShowNativeExpressAdView()144        {145            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);146        }147        public void HideNativeExpressAdView()148        {149            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);150        }151        public void DestroyNativeExpressAdView()152        {153            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);154        }155        public string MediationAdapterClassName()156        {157            Debug.Log("Dummy " + MethodBase.GetCurrentMethod().Name);158            return null;159        }160    }161}...

Full Screen

Full Screen

DecoratorTests.cs

Source:DecoratorTests.cs Github

copy

Full Screen

...10        [Fact]11        public void GetInner_Returns_Inner_Object_From_ObjectWrapper()12        {13            // Arrange14            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();15            DummyObjectWrapper dummyObjectWrapper = new DummyObjectWrapper(dummyInnerObject);16            IBaseInterface dummyBase = dummyObjectWrapper as IBaseInterface;17            // Act18            DummyAggregatedClass innerObject = Decorator.GetInner(dummyBase) as DummyAggregatedClass;19            // Assert20            Assert.Same(dummyInnerObject, innerObject);21        }22        [Fact]23        public void GetInner_Returns_InnerMost_Object_From_ObjectWrapper()24        {25            // Arrange26            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();27            DummyObjectWrapper dummyObjectWrapper = new DummyObjectWrapper(dummyInnerObject);28            DummyDoubleLayerWrapper dummyDoubleLayerWrapper = new DummyDoubleLayerWrapper(dummyObjectWrapper);29            IBaseInterface dummyBase = dummyDoubleLayerWrapper as IBaseInterface;30            // Act31            DummyAggregatedClass innerObject = Decorator.GetInner(dummyBase) as DummyAggregatedClass;32            // Assert33            Assert.Same(dummyInnerObject, innerObject);34        }35        [Fact]36        public void GetInner_Call_On_InnerObject_Returns_InnerObject()37        {38            // Arrange39            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();40            IBaseInterface dummyBase = dummyInnerObject as IBaseInterface;41            // Act42            DummyAggregatedClass innerObject = Decorator.GetInner(dummyBase) as DummyAggregatedClass;43            // Assert44            Assert.Same(dummyInnerObject, innerObject);45        }46        [Fact]47        public void GetInner_Call_On_Wrapper_Which_Does_Not_Contain_InnerObject_Returns_Wrapper()48        {49            // Arrange50            DummyWrapper dummyWrapper = new DummyWrapper();51            IBaseInterface dummyBase = dummyWrapper as IBaseInterface;52            // Act53            DummyWrapper innerObject = Decorator.GetInner(dummyBase) as DummyWrapper;54            // Assert55            Assert.Same(dummyWrapper, innerObject);56        }57        [Fact]58        public void GetInner_Returns_Itself_From_AnyClass_Which_Does_Not_Implement_Base_Interface()59        {60            // Arrange61            Mock<object> dummyClass = new Mock<object>();62            // Act63            object innerObject = Decorator.GetInner(dummyClass.Object);64            // Assert65            Assert.Same(dummyClass.Object, innerObject);66        }67        [Fact]68        public void GetInner_Returns_Null_When_Null_Is_Passed()69        {70            // Arrange71            object nullValue = null;72            // Act73            object innerObject = Decorator.GetInner(nullValue);74            // Assert75            Assert.Null(innerObject);76        }77        [Fact]78        public void GetInner_Returns_Inner_Object_From_ObjectWrapper_Which_Wraps_Itself()79        {80            // Arrange81            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();82            DummyBaseWrapper dummyBaseWrapper = new DummyBaseWrapper(dummyInnerObject);83            IBaseInterface dummyBase = dummyBaseWrapper as IBaseInterface;84            // Act85            DummyBaseWrapper innerObject = Decorator.GetInner(dummyBase) as DummyBaseWrapper;86            // Assert87            Assert.Same(dummyBaseWrapper, innerObject);88        }89        private interface IBaseInterface { }90        private class DummyAggregatedClass : IBaseInterface { }91        private class DummyWrapper : IBaseInterface { }92        private class DummyObjectWrapper : IBaseInterface, IDecorator<DummyAggregatedClass>93        {94            private readonly DummyAggregatedClass _inner;95            public DummyObjectWrapper(DummyAggregatedClass innerObject)96            {97                _inner = innerObject;98            }99            public DummyAggregatedClass Inner100            {101                get { return _inner; }102            }103        }104        private class DummyDoubleLayerWrapper : IBaseInterface, IDecorator<DummyObjectWrapper>105        {106            private readonly DummyObjectWrapper _inner;107            public DummyDoubleLayerWrapper(DummyObjectWrapper innerObject)108            {109                _inner = innerObject;110            }111            public DummyObjectWrapper Inner112            {113                get { return _inner; }114            }115        }116        private class DummyBaseWrapper : IBaseInterface, IDecorator<IBaseInterface>117        {118            private readonly IBaseInterface _inner;119            public DummyBaseWrapper(IBaseInterface innerObject)120            {121                _inner = innerObject;122            }123            public IBaseInterface Inner124            {125                get { return this; }126            }127        }128    }129}...

Full Screen

Full Screen

VirtualPathProviderTest.cs

Source:VirtualPathProviderTest.cs Github

copy

Full Screen

...34using System.Web.Caching;35using System.Web.Hosting;36using NUnit.Framework;37namespace MonoTests.System.Web.Hosting {38	class DummyVPP : VirtualPathProvider {39		public override bool FileExists (string virtualPath)40		{41			bool de = base.FileExists (virtualPath);42			return de;43		}44		public override bool DirectoryExists (string virtualDir)45		{46			bool de = base.DirectoryExists (virtualDir);47			return de;48		}49		public override VirtualFile GetFile (string virtualPath)50		{51			VirtualFile vf = base.GetFile (virtualPath);52			return vf;53		}54		public override string GetFileHash (string virtualPath, IEnumerable dependencies)55		{56			return base.GetFileHash (virtualPath, dependencies);57		}58		public override VirtualDirectory GetDirectory (string virtualDir)59		{60			VirtualDirectory vd = base.GetDirectory (virtualDir);61			return vd;62		}63		public override CacheDependency GetCacheDependency (string virtualPath,64						IEnumerable virtualPathDependencies, DateTime utcStart)65		{66			CacheDependency cd = base.GetCacheDependency (virtualPath, virtualPathDependencies, utcStart);67			return cd;68		}69	}70	[TestFixture]71	public class VirtualPathProviderTest {72		// Unhosted tests: not running inside an ASP.NET appdomain.73		// Some tests may yield different results when hosted. I'll add those later.74		[Test]75		public void FileExists1 ()76		{77			DummyVPP dummy = new DummyVPP ();78			Assert.IsFalse (dummy.FileExists ("hola.aspx"));79		}80		[Test]81		public void DirectoryExists1 ()82		{83			DummyVPP dummy = new DummyVPP ();84			Assert.IsFalse (dummy.DirectoryExists ("hola"));85		}86		[Test]87		public void GetFile1 ()88		{89			DummyVPP dummy = new DummyVPP ();90			Assert.IsNull (dummy.GetFile ("index.aspx"));91		}92		[Test]93		public void GetFileHash1 ()94		{95			DummyVPP dummy = new DummyVPP ();96			Assert.IsNull (dummy.GetFileHash (null, null));97		}98		[Test]99		public void GetFileHash2 ()100		{101			DummyVPP dummy = new DummyVPP ();102			Assert.IsNull (dummy.GetFileHash ("something", null));103		}104		[Test]105		public void GetDirectory1 ()106		{107			DummyVPP dummy = new DummyVPP ();108			Assert.IsNull (dummy.GetDirectory ("some_directory"));109		}110		[Test]111		public void GetCacheDependency1 ()112		{113			DummyVPP dummy = new DummyVPP ();114			Assert.IsNull (dummy.GetCacheDependency (null, null, DateTime.UtcNow));115		}116		[Test]117		public void GetCacheKey1 ()118		{119			DummyVPP dummy = new DummyVPP ();120			Assert.IsNull (dummy.GetCacheKey ("index.aspx"));121		}122		[Test]123		[ExpectedException (typeof (NullReferenceException))]124		public void OpenFile1 ()125		{126			VirtualPathProvider.OpenFile ("index.aspx");127		}128		[Test]129		public void CombineVirtualPaths1 ()130		{131			DummyVPP dummy = new DummyVPP ();132			Assert.AreEqual ("/otherroot", dummy.CombineVirtualPaths ("/root", "/otherroot"));133		}134		[Test]135		public void CombineVirtualPaths2 ()136		{137			DummyVPP dummy = new DummyVPP ();138			Assert.AreEqual ("/otherleaf", dummy.CombineVirtualPaths ("/root", "otherleaf"));139		}140		[Test]141		public void CombineVirtualPaths3 ()142		{143			DummyVPP dummy = new DummyVPP ();144			Assert.AreEqual ("/otherleaf/index.aspx", dummy.CombineVirtualPaths ("/root", "otherleaf/index.aspx"));145		}146		[Test]147        [Category ("NotWorking")]148		public void CombineVirtualPaths4 ()149		{150			DummyVPP dummy = new DummyVPP ();151			Assert.AreEqual ("/otherleaf/index.aspx", dummy.CombineVirtualPaths ("/root", "./otherleaf/index.aspx"));152		}153		[Test]154		[ExpectedException (typeof (ArgumentException))]155		public void CombineVirtualPaths5 ()156		{157			DummyVPP dummy = new DummyVPP ();158			dummy.CombineVirtualPaths ("root", "./otherleaf/index.aspx");159		}160	}161	162}163#endif...

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3    {4        static void Main(string[] args)5        {6            Dummy d = new Dummy();7            d.Print();8        }9    }10}11using C;12{13    {14        static void Main(string[] args)15        {16            Dummy d = new Dummy();17            d.Print();18        }19    }20}21using D;22{23    {24        static void Main(string[] args)25        {26            Dummy d = new Dummy();27            d.Print();28        }29    }30}31using E;32{33    {34        static void Main(string[] args)35        {36            Dummy d = new Dummy();37            d.Print();38        }39    }40}41using F;42{43    {44        static void Main(string[] args)45        {46            Dummy d = new Dummy();47            d.Print();48        }49    }50}51using G;52{53    {54        static void Main(string[] args)55        {56            Dummy d = new Dummy();57            d.Print();58        }59    }60}61using H;62{63    {64        static void Main(string[] args)65        {66            Dummy d = new Dummy();67            d.Print();68        }69    }70}71using I;72{73    {74        static void Main(string[] args)75        {76            Dummy d = new Dummy();77            d.Print();78        }79    }80}81using J;82{83    {84        static void Main(string[] args)85        {86            Dummy d = new Dummy();87            d.Print();88        }89    }90}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3    {4        static void Main(string[] args)5        {6            Dummy d = new Dummy();7            d.Display();8        }9    }10}11using C;12{13    {14        static void Main(string[] args)15        {16            Dummy d = new Dummy();17            d.Display();18        }19    }20}21using D;22{23    {24        static void Main(string[] args)25        {26            Dummy d = new Dummy();27            d.Display();28        }29    }30}31using E;32{33    {34        static void Main(string[] args)35        {36            Dummy d = new Dummy();37            d.Display();38        }39    }40}41using F;42{43    {44        static void Main(string[] args)45        {46            Dummy d = new Dummy();47            d.Display();48        }49    }50}51using G;52{53    {54        static void Main(string[] args)55        {56            Dummy d = new Dummy();57            d.Display();58        }59    }60}61using H;62{63    {64        static void Main(string[] args)65        {66            Dummy d = new Dummy();67            d.Display();68        }69    }70}71using I;72{73    {74        static void Main(string[] args)75        {76            Dummy d = new Dummy();77            d.Display();78        }79    }80}81using J;82{83    {84        static void Main(string[] args)85        {86            Dummy d = new Dummy();87            d.Display();88        }89    }90}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3    {4        static void Main(string[] args)5        {6            Dummy obj = new Dummy();7            obj.Display();8        }9    }10}11using C;12{13    {14        static void Main(string[] args)15        {16            Dummy obj = new Dummy();17            obj.Display();18        }19    }20}21using D;22{23    {24        static void Main(string[] args)25        {26            Dummy obj = new Dummy();27            obj.Display();28        }29    }30}31using E;32{33    {34        static void Main(string[] args)35        {36            Dummy obj = new Dummy();37            obj.Display();38        }39    }40}41using F;42{43    {44        static void Main(string[] args)45        {46            Dummy obj = new Dummy();47            obj.Display();48        }49    }50}51using G;52{53    {54        static void Main(string[] args)55        {56            Dummy obj = new Dummy();57            obj.Display();58        }59    }60}61using H;62{63    {64        static void Main(string[] args)65        {66            Dummy obj = new Dummy();67            obj.Display();68        }69    }70}71using I;72{73    {74        static void Main(string[] args)75        {76            Dummy obj = new Dummy();77            obj.Display();78        }79    }80}81using J;82{83    {84        static void Main(string[] args)85        {86            Dummy obj = new Dummy();87            obj.Display();88        }89    }90}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3  static void Main()4  {5    Dummy d = new Dummy();6    d.Display();7  }8}9using C;10{11  static void Main()12  {13    Dummy d = new Dummy();14    d.Display();15  }16}17using D;18{19  static void Main()20  {21    Dummy d = new Dummy();22    d.Display();23  }24}25using E;26{27  static void Main()28  {29    Dummy d = new Dummy();30    d.Display();31  }32}33using F;34{35  static void Main()36  {37    Dummy d = new Dummy();38    d.Display();39  }40}41using G;42{43  static void Main()44  {45    Dummy d = new Dummy();46    d.Display();47  }48}49using H;50{51  static void Main()52  {53    Dummy d = new Dummy();54    d.Display();55  }56}57using I;58{59  static void Main()60  {61    Dummy d = new Dummy();62    d.Display();63  }64}65using J;66{67  static void Main()68  {69    Dummy d = new Dummy();70    d.Display();71  }72}73using K;74{75  static void Main()76  {77    Dummy d = new Dummy();78    d.Display();79  }80}81using L;82{83  static void Main()84  {85    Dummy d = new Dummy();86    d.Display();87  }88}89using M;

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using System;2{3    {4        public static void Main()5        {6            B.Dummy d = new B.Dummy();7            d.Print();8        }9    }10}11using System;12{13    {14        public static void Main()15        {16            B.Dummy d = new B.Dummy();17            d.Print();18        }19    }20}21using System;22{23    {24        public static void Main()25        {26            B.Dummy d = new B.Dummy();27            d.Print();28        }29    }30}31using System;32{33    {34        public static void Main()35        {36            B.Dummy d = new B.Dummy();37            d.Print();38        }39    }40}41using System;42{43    {44        public static void Main()45        {46            B.Dummy d = new B.Dummy();47            d.Print();48        }49    }50}51using System;52{53    {54        public static void Main()55        {56            B.Dummy d = new B.Dummy();57            d.Print();58        }59    }60}61using System;62{63    {64        public static void Main()65        {66            B.Dummy d = new B.Dummy();67            d.Print();68        }69    }70}71using System;72{73    {74        public static void Main()75        {76            B.Dummy d = new B.Dummy();77            d.Print();78        }79    }80}81using System;82{83    {84        public static void Main()85        {

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3    {4        public static void Main()5        {6            Dummy d = new Dummy();7            d.Display();8        }9    }10}11using A;12{13    {14        public void Display()15        {16            System.Console.WriteLine("Hello World");17        }18    }19}20Microsoft (R) Visual C# Compiler version 2.0.50727.4221for Microsoft (R) .NET Framework version 2.0.50727.42221.cs(1) : warning CS1633: The file '1.cs' has no types or namespaces defined232.cs(1) : warning CS1633: The file '2.cs' has no types or namespaces defined243.cs(1) : warning CS1633: The file '3.cs' has no types or namespaces defined25Microsoft (R) Visual C# Compiler version 2.0.50727.4226for Microsoft (R) .NET Framework version 2.0.50727.42271.cs(1) : warning CS1633: The file '1.cs' has no types or namespaces defined282.cs(1) : warning CS1633: The file '2.cs' has no types or namespaces defined293.cs(1) : warning CS1633: The file '3.cs' has no types or namespaces defined30using System;31{32    {

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3   public static void Main()4   {5      Dummy d = new Dummy();6   }7}8Microsoft (R) Visual C# 2003 Compiler version 7.10.3077.092.cs(4,23): error CS0012: The type `B.Dummy' is defined in an assembly that is not referenced. You must add a reference to assembly `B, Version=

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3    public static void Main()4    {5        Dummy d = new Dummy();6        d.Display();7    }8}

Full Screen

Full Screen

Dummy

Using AI Code Generation

copy

Full Screen

1using B;2{3    static void Main()4    {5        Dummy d = new Dummy();6    }7}

Full Screen

Full Screen

Nunit tutorial

Nunit is a well-known open-source unit testing framework for C#. This framework is easy to work with and user-friendly. LambdaTest’s NUnit Testing Tutorial provides a structured and detailed learning environment to help you leverage knowledge about the NUnit framework. The NUnit tutorial covers chapters from basics such as environment setup to annotations, assertions, Selenium WebDriver commands, and parallel execution using the NUnit framework.

Chapters

  1. NUnit Environment Setup - All the prerequisites and setup environments are provided to help you begin with NUnit testing.
  2. NUnit With Selenium - Learn how to use the NUnit framework with Selenium for automation testing and its installation.
  3. Selenium WebDriver Commands in NUnit - Leverage your knowledge about the top 28 Selenium WebDriver Commands in NUnit For Test Automation. It covers web browser commands, web element commands, and drop-down commands.
  4. NUnit Parameterized Unit Tests - Tests on varied combinations may lead to code duplication or redundancy. This chapter discusses how NUnit Parameterized Unit Tests and their methods can help avoid code duplication.
  5. NUnit Asserts - Learn about the usage of assertions in NUnit using Selenium
  6. NUnit Annotations - Learn how to use and execute NUnit annotations for Selenium Automation Testing
  7. Generating Test Reports In NUnit - Understand how to use extent reports and generate reports with NUnit and Selenium WebDriver. Also, look into how to capture screenshots in NUnit extent reports.
  8. Parallel Execution In NUnit - Parallel testing helps to reduce time consumption while executing a test. Deep dive into the concept of Specflow Parallel Execution in NUnit.

NUnit certification -

You can also check out the LambdaTest Certification to enhance your learning in Selenium Automation Testing using the NUnit framework.

YouTube

Watch this tutorial on the LambdaTest Channel to learn how to set up the NUnit framework, run tests and also execute parallel testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful