Fail() публичный статический Метод

public static Fail ( string msg ) : void
msg string
Результат void
Пример #1
0
		public void Send_SpecifiedPickupDirectory_PickupDirectoryLocation_IllegalChars ()
		{
			smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
			smtp.PickupDirectoryLocation = "\0abc";
			try {
				smtp.Send ("*****@*****.**", "*****@*****.**",
					"introduction", "hello");
				Assert.Fail ("#1");
			} catch (SmtpException ex) {
				// Failure sending email
				Assert.AreEqual (typeof (SmtpException), ex.GetType (), "#2");
				Assert.IsNotNull (ex.InnerException, "#3");
				Assert.AreEqual (typeof (ArgumentException), ex.InnerException.GetType (), "#4");
				Assert.IsNotNull (ex.Message, "#5");
				Assert.AreEqual (SmtpStatusCode.GeneralFailure, ex.StatusCode, "#6");

				// Illegal characters in path
				ArgumentException inner = (ArgumentException) ex.InnerException;
				Assert.IsNull (inner.InnerException, "#7");
				Assert.IsNotNull (inner.Message, "#8");
				Assert.IsNull (inner.ParamName, "#9");
			}
		}
Пример #2
0
        public void NextLowerUpper_LongRange_Bounds()
        {
            int            sampleCount = 10000000;
            XorShiftRandom rng         = new XorShiftRandom();

            System.Random sysRng = new System.Random();

            int maxValHalf = int.MaxValue / 2;

            double[] sampleArr = new double[sampleCount];

            for (int i = 0; i < sampleCount; i++)
            {
                int lowerBound = -(maxValHalf + (sysRng.Next() / 2));
                int upperBound = (maxValHalf + (sysRng.Next() / 2));
                int sample     = rng.Next(lowerBound, upperBound);

                if (sample < lowerBound || sample >= upperBound)
                {
                    Assert.Fail();
                }
            }
        }
        public void TestCleanup()
        {
            try
            {
                this.Listener.Stop();
            }
            catch (Exception)
            {
            }

            if (this.EtwSession.FailureDetected)
            {
                Assert.Fail("Read test output. There are errors found in application trace.");
            }

            try
            {
                this.EtwSession.Stop();
            }
            catch (Exception)
            {
            }
        }
        private void ParseWithoutError(string filePath, ProjectType projType)
        {
            var result = new RapidXamlDocument();

            var text = File.ReadAllText(filePath);

            var snapshot = new FakeTextSnapshot();

            try
            {
                XamlElementExtractor.Parse(
                    projType,
                    Path.GetFileName(filePath),
                    snapshot,
                    text,
                    RapidXamlDocument.GetAllProcessors(projType, string.Empty, DefaultTestLogger.Create()),
                    result.Tags);
            }
            catch (Exception exc)
            {
                Assert.Fail($"Parsing failed for '{filePath}'{Environment.NewLine}{exc}");
            }
        }
Пример #5
0
        public void TestCallBackServiceUnknowMessageEx()
        {
            var msg = new MessageFromESB
            {
                MessageTypeID = "TestUnknowTypeMessage",
                Body          = "",
                SenderName    = "TestSender"
            };

            try
            {
                var cb = new CallbackSubscriber();
                cb.AcceptMessage(msg);
            }
            catch (UnknowMessageTypeException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Assert.Fail($"Произошло неожиданное исключение - {ex.Message}");
            }
        }
Пример #6
0
        public void TestConnectByDomain()
        {
            using (var proxy = new Socks4aProxyListener()) {
                proxy.Start(IPAddress.Loopback, 0);

                var    socks  = new Socks4aClient(proxy.IPAddress.ToString(), proxy.Port);
                Socket socket = null;

                try {
                    socket = socks.Connect("www.google.com", 80, 10 * 1000);
                    socket.Disconnect(false);
                } catch (TimeoutException) {
                    Assert.Inconclusive("Timed out.");
                } catch (Exception ex) {
                    Assert.Fail(ex.Message);
                } finally {
                    if (socket != null)
                    {
                        socket.Dispose();
                    }
                }
            }
        }
Пример #7
0
        public void ProfileInsert()
        {
            Stopwatch watch = Stopwatch.StartNew();

            try
            {
                var data = DataAccessLayer.Instance.ProfileInsert("BLAKE-0", "Blake", false, DateTime.Now, DateTime.Now);

                data.Read();

                _profileUniqueID = data.GetInt32("UniqueID");

                data.Close();
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }

            Assert.IsTrue(true);

            Console.WriteLine("Time: {0} ms", watch.ElapsedMilliseconds);
        }
Пример #8
0
		public void LoadPostData ()  //Just flow and not implementation detail
		{
			WebTest t = new WebTest (PageInvoker.CreateOnLoad (LoadPostData_Load));
			string html = t.Run ();
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls.Add ("RadioButton1");
			fr.Controls["__EVENTTARGET"].Value = "__Page";
			fr.Controls["__EVENTARGUMENT"].Value = "";
			fr.Controls ["RadioButton1"].Value = "RadioButton1";
			t.Request = fr;
			t.Run ();

			ArrayList eventlist = t.UserData as ArrayList;
			if (eventlist == null)
				Assert.Fail ("User data does not been created fail");
			Assert.AreEqual ("ControlLoad", eventlist[0], "Live Cycle Flow #1");
			Assert.AreEqual ("PageLoad", eventlist[1], "Live Cycle Flow #2");
			Assert.AreEqual ("ControlLoad", eventlist[2], "Live Cycle Flow #3");
			Assert.AreEqual ("LoadPostData", eventlist[3], "Live Cycle Flow #4");

		}
Пример #9
0
        public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor()
        {
            // arrange
            IInstanceInterceptor interceptor = new InterfaceInterceptor();
            HasSomeProperties    target      = new HasSomeProperties();
            object proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IInterfaceOne));

            // act
            Exception exception = null;

            try
            {
                ((IInterfaceOne)proxy).TargetMethod();
                Assert.Fail("should have thrown");
            }
            catch (NotImplementedException e)
            {
                exception = e;
            }

            // assert
            Assert.IsNotNull(exception);
        }
Пример #10
0
        private void EnumerateAndReadShouldNotChangeEnumerationOrder(string folderRelativePath)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                NativeTests.EnumerateAndReadDoesNotChangeEnumerationOrder(folderRelativePath).ShouldEqual(true);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                string[] entries = Directory.GetFileSystemEntries(folderRelativePath);
                foreach (string entry in entries)
                {
                    File.ReadAllText(entry);
                }

                string[] postReadEntries = Directory.GetFileSystemEntries(folderRelativePath);
                Enumerable.SequenceEqual(entries, postReadEntries)
                .ShouldBeTrue($"Entries are not the same after reading. Orignial list:\n{string.Join(",", entries)}\n\nAfter read:\n{string.Join(",", postReadEntries)}");
            }
            else
            {
                Assert.Fail("Unsupported platform");
            }
        }
Пример #11
0
        public void CanDoPolymorphicMessageDispatch()
        {
            var manualResetEvent = new ManualResetEvent(false);
            var handler          = new SomeHandler(manualResetEvent);

            activateHandlers.UseHandler(handler);

            receiveMessages.Deliver(new Message
            {
                Messages = new object[]
                {
                    new PolymorphicMessage()
                }
            });

            if (!manualResetEvent.WaitOne(TimeSpan.FromSeconds(4)))
            {
                Assert.Fail("Did not receive messages within timeout");
            }

            handler.FirstMessageHandled.ShouldBe(true);
            handler.SecondMessageHandled.ShouldBe(true);
        }
Пример #12
0
        private void AssertNonLooping(String path)
        {
            var reader = new CSVReader(new AdapterInputSource(path));

            String[] nextRecord = reader.GetNextRecord();
            var      expected   = new[] { "first line", "1" };

            Assert.AreEqual(expected, nextRecord);

            nextRecord = reader.GetNextRecord();
            expected   = new[] { "second line", "2" };
            Assert.AreEqual(expected, nextRecord);

            try {
                reader.GetNextRecord();
                Assert.Fail();
            }
            catch (EndOfStreamException ex) {
                // Expected
            }

            reader.Close();
        }
Пример #13
0
        public void Cannot_assign_roles_with_normal_user()
        {
            var newUser = RegisterNewUser(autoLogin: true);

            try
            {
                var response = ServiceClient.Send(
                    new AssignRoles {
                    UserName    = newUser.UserName,
                    Roles       = { RoleName1, RoleName2 },
                    Permissions = { Permission1, Permission2 }
                });

                response.PrintDump();
                Assert.Fail("Should not be allowed");
            }
            catch (WebServiceException webEx)
            {
                Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Forbidden));
                //StatusDescription is ignored in WebDevServer
                //Assert.That(webEx.StatusDescription, Is.EqualTo("Invalid Role"));
            }
        }
Пример #14
0
        public void FindMigrations_HasTwoMigrationsWithSameVersion_Throws()
        {
            using (_mocks.Record())
            {
                _files.Add("001_migration2.cs");
                _files.Add("001_migration.cs");
                SetupResult.For(_configuration.MigrationsDirectory).Return("MigrationsDirectory");
                SetupResult.For(_fileSystem.GetFiles("MigrationsDirectory")).Return(_files.ToArray());
                SetupResult.For(_fileSystem.GetDirectories("MigrationsDirectory")).Return(new string[0]);
                SetupResult.For(_namer.ToCamelCase("migration")).Return("Migration");
            }

            try
            {
                List <MigrationReference> migrations = new List <MigrationReference>(_target.FindMigrations());
            }
            catch (DuplicateMigrationVersionException)
            {
                return;
            }

            Assert.Fail("Should have thrown DuplicateMigrationVersionException");
        }
        public void ShouldPreventRemovalAfterLockTimeSpan()
        {
            _subject.LockAge = TimeSpan.FromSeconds(2);
            var key1 = "TheTestKey7";

            _subject.Add(key1, "value");
            var key2 = "TheTestKey8";

            _subject.Add(key2, "value8");
            _subject.Remove(key2).Should().BeTrue("Can remove key that is young enough");
            Thread.Sleep(3000);

            try
            {
                _subject.Remove(key1);
            }
            catch (Exception)
            {
                return;
            }

            Assert.Fail("Should throw when trying to remove key that is too old");
        }
Пример #16
0
        public void NegativeTestZeroingAndCloseAllAccounts()
        {
            var client = new Client("client1");

            client.OpenSavingsAccount(1000M);
            client.OpenSavingsAccount(0M);
            client.OpenCumulativeAccount(1000M);
            client.OpenCumulativeAccount(0M);
            client.OpenCheckingAccount(1000M);
            client.OpenCheckingAccount(0M);
            client.OpenMetalAccount(MetalType.Argentum, 100, 500M);
            client.OpenMetalAccount(MetalType.Aurum, 100, 1500M);
            client.OpenMetalAccount(MetalType.Platinum, 100, 2500M);

            client.ZeroingAndCloseAllAccounts();
            
            try
            {
                client.ZeroingAndCloseAllAccounts();
                Assert.Fail();
            }
            catch (Exception) { }
        }
        public void RoundTripBinaryContent()
        {
            byte[] data   = new byte[512];
            Random random = new Random();

            random.NextBytes(data);

            Guid id = this.source.InsertBinary(data, "na");

            Assert.AreNotEqual <Guid>(Guid.Empty, id, "Identifier not set.");

            byte[] returnedData = this.source.SelectBinary(id);
            Assert.IsNotNull(returnedData);
            Assert.AreEqual <int>(data.Length, returnedData.Length, "Data is inconsistant.");

            for (int i = 0; i < data.Length; i++)
            {
                if (data[i] != returnedData[i])
                {
                    Assert.Fail("Data is inconsistant.");
                }
            }
        }
Пример #18
0
        public void GetStream_Resource_NonStream()
        {
            ResourceManager rm = ResourceManager.
                                 CreateFileBasedResourceManager("MyResources", "Test/resources", null);

            try
            {
                rm.GetStream("HelloWorld", CultureInfo.InvariantCulture);
                Assert.Fail("#1");
            }
            catch (InvalidOperationException ex)
            {
                // Resource 'HelloWorld' was not a Stream - call
                // GetObject instead
                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType(), "#2");
                Assert.IsNull(ex.InnerException, "#3");
                Assert.IsNotNull(ex.Message, "#4");
            }
            finally
            {
                rm.ReleaseAllResources();
            }
        }
Пример #19
0
        public void GenerateRandomNumberWithStaticInputsExpectedARandomNumberToBeOutput()
        {
            const int Start = 10;
            const int End   = 20;

            SetupArguments(ActivityStrings.RandomActivityDataListWithData, ActivityStrings.RandomActivityDataListShape, enRandomType.Numbers, Start.ToString(CultureInfo.InvariantCulture), End.ToString(CultureInfo.InvariantCulture), string.Empty, "[[OutVar1]]");

            var result = ExecuteProcess();

            GetScalarValueFromEnvironment(result.Environment, "OutVar1", out string actual, out string error);
            int.TryParse(actual, out int actualNum);

            // remove test datalist ;)

            if (string.IsNullOrEmpty(error))
            {
                Assert.IsTrue(actualNum >= Start && actualNum <= End);
            }
            else
            {
                Assert.Fail("The following errors occurred while retrieving datalist items\r\nerrors:{0}", error);
            }
        }
        public void GetInstance_WithoutLifetimeScope_ThrowsExpectedException()
        {
            // Arrange
            var container = new Container();

            container.RegisterLifetimeScope <ICommand, ConcreteCommand>();

            try
            {
                // Act
                var firstInstance = container.GetInstance <ICommand>();

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ActivationException ex)
            {
                Assert.IsTrue(ex.Message.Contains(
                                  "The ICommand is registered as 'Lifetime Scope' lifestyle, but the instance is requested " +
                                  "outside the context of a Lifetime Scope."),
                              "Actual message: " + ex.Message);
            }
        }
        public async Task SetWebProxyAsync_DoesNotThrowUriException()
        {
            Configuration configuration = new Configuration(
                Environment.DEVELOPMENT,
                "integration_merchant_id",
                "integration_public_key",
                "integration_private_key"
                );

            configuration.WebProxy = new WebProxy("http://localhost:3000");

            BraintreeService service = new BraintreeService(configuration);

            try {
                await service.GetAsync(service.MerchantPath() + "/non-existent-route");

                Assert.Fail("Should have thrown exception");
            } catch (System.UriFormatException) {
                Assert.Fail("Setting WebProxy should not throw a URI exception");
            } catch (NotFoundException) {
                // expected
            }
        }
        public void Coopertiv_Open_Pause_Close_Window_From_MenuForm()
        {
            var        cooperativ = new CoopForm();
            MethodInfo MethodbuttonStart_Click = cooperativ.GetType().GetMethod("buttonStart_Click", BindingFlags.NonPublic | BindingFlags.Instance);

            MethodbuttonStart_Click.Invoke(cooperativ, new object[] { null, null });
            if (cooperativ.buttonStart.Text != "   Pause")
            {
                Assert.Fail();
            }
            MethodbuttonStart_Click.Invoke(cooperativ, new object[] { null, null });
            if (cooperativ.buttonStart.Text != "   Resume")
            {
                Assert.Fail();
            }
            MethodInfo MethodExit = cooperativ.GetType().GetMethod("Exit", BindingFlags.NonPublic | BindingFlags.Instance);

            MethodExit.Invoke(cooperativ, new object[] { });
            if (cooperativ.IsAccessible != false)
            {
                Assert.Fail();
            }
        }
Пример #23
0
 public void TestNoEnterLastLineReadValue()
 {
     using (CsvReader reader = new CsvReader(TestCSVFileNames[3]))
     {
         int   numberOfLines   = 0;
         float lastColumnValue = float.NaN;
         while (reader.LoadLine(out int columns))
         {
             if ((columns == 0) & (numberOfLines != 4))
             {
                 Assert.Fail("There was a blank line besides at the end of the file!");
             }
             else if (columns > 0)
             {
                 Assert.AreEqual(5, columns);
             }
             numberOfLines++;
             reader.Get(out lastColumnValue, 4);
         }
         Assert.AreEqual(4, numberOfLines);
         Assert.AreEqual(0.1314f, lastColumnValue);
     }
 }
Пример #24
0
        public void TestCommand()
        {
            BytesMessage message = new BytesMessage();

            // Test that a BytesMessage is created in WriteOnly mode.
            try
            {
                byte[] content = message.Content;
                content.SetValue(0, 0);
                Assert.Fail("Should have thrown an exception");
            }
            catch
            {
            }

            Assert.IsTrue(!message.ReadOnlyBody);
            Assert.IsTrue(!message.ReadOnlyProperties);

            message.Reset();

            Assert.IsNull(message.Content);
            Assert.IsTrue(message.ReadOnlyBody);
        }
        public async Task ReceiveBatch()
        {
            var random = new Random();
            var count = random.Next(1, 11);
            var sent = new List<Guid>();
            var bq = new BusQueueClient(new QueueClient(connection, queue.Name));
            //for (var i = 0; i < count; i++)
            //{
            //    var expected = Guid.NewGuid();
            //    var msg = new Message(expected);
            //    await bq.Send(msg);
            //    sent.Add(expected);
            //}

            //var got = await bq.RecieveBatch(count, TimeSpan.FromSeconds(10));
            //foreach (var msg in got)
            //{
            //    var result = msg.GetBody<Guid>();
            //    Assert.IsTrue(sent.Contains(result));
            //}

            Assert.Fail();
        }
        private void TestEnqueue(Func <int, PriorityQueue <object> > func)
        {
            {
                PriorityQueue <object> queue = func(1);
                queue.Enqueue(null);
                queue.Enqueue(null);
            }

            try
            {
                PriorityQueue <object> queue = func(1);
                queue.Enqueue(1);
                queue.Enqueue("1");
                Assert.Fail("ArgumentException should have been thrown.");
            }
            catch (ArgumentException)
            { }

            try
            {
                PriorityQueue <object> queue = func(1);
                queue.Enqueue(new object());
                queue.Enqueue(new object());
                Assert.Fail("ArgumentException should have been thrown.");
            }
            catch (ArgumentException)
            { }

            {
                PriorityQueue <object> queue = func(PriorityQueueTest.Size);
                for (int i = 0; i < PriorityQueueTest.Size; ++i)
                {
                    Assert.AreEqual(i, queue.Count);
                    queue.Enqueue(i);
                }
            }
        }
Пример #27
0
        public void SetSmallKernelBufferSizeGetPacketsErrorTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
                communicator.SetKernelBufferSize(10);
                Packet packet = _random.NextEthernetPacket(100, SourceMac, DestinationMac);
                communicator.SendPacket(packet);
                Exception exception = null;
                Thread    thread    = new Thread(delegate()
                {
                    try
                    {
                        communicator.ReceivePackets(1, delegate { });
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                });
                thread.Start();
                if (!thread.Join(TimeSpan.FromSeconds(5)))
                {
                    thread.Abort();
                }

                if (exception != null)
                {
                    throw exception;
                }
            }

            Assert.Fail();
        }
Пример #28
0
        public async Task RenterService_AddRenterAsync_Test()
        {
            try
            {
                using (var db = new DatabaseContext(dbContextOpt.Options))
                {
                    var renterModel = new RenterModel
                    {
                        Name       = "Jhon",
                        ContactNo  = "9876543210",
                        Address    = "General Maxilom Avenue",
                        Profession = "Front Desk",
                        PropertyId = Guid.Parse("6B4621F3-7102-4953-8D5F-75F71B1729E6")
                    };

                    var renter = new Renter
                    {
                        Id         = Guid.NewGuid(),
                        Name       = renterModel.Name,
                        ContactNo  = renterModel.ContactNo,
                        Address    = renterModel.Address,
                        Profession = renterModel.Profession,
                        PropertyId = renterModel.PropertyId
                    };

                    db.Renter.Add(renter);
                    var result = await db.SaveChangesAsync();

                    Assert.IsTrue(result == 1);
                }
            }
            catch (Exception ex)
            {
                logService.Log("Add Renter", ex.InnerException.Message, ex.Message, ex.StackTrace);
                Assert.Fail();
            }
        }
Пример #29
0
        public void FileLogging_Write_Message_And_IDBCommand()
        {
            FileLog fl = new FileLog();

            fl.LogFile(_pathToFile);

            TreeMonDbContext context = new TreeMonDbContext("MSSQL_TEST");
            IDbCommand       cmd     = context.Database.Connection.CreateCommand();

            cmd.CommandText = "Select * from test";
            IDbDataParameter p = cmd.CreateParameter();

            p.ParameterName = "testParam";
            p.Value         = "testValue";
            cmd.Parameters.Add(p);

            fl.Write("FileLoggingWrite_Message", cmd);

            if (!File.Exists(_pathToFile))
            {
                Assert.Fail("Log file doesn't exist " + _pathToFile);
            }

            string tmp = File.ReadAllText(_pathToFile);

            Assert.IsTrue(tmp.Contains("FileLoggingWrite_Message"));
            Assert.IsTrue(tmp.Contains("Select * from test"));
            Assert.IsTrue(tmp.Contains("testParam: testValue"));

            try
            {
                File.Delete(_pathToFile);
            }catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Пример #30
0
        public void CanSolveForRandomVector(int order)
        {
            for (var iteration = 5; iteration > 3; iteration--)
            {
                var matrixA = MatrixLoader.GenerateRandomDenseMatrix(order, order);
                var vectorb = MatrixLoader.GenerateRandomDenseVector(order);

                var monitor = new Iterator(new IIterationStopCriterium[]
                {
                    new IterationCountStopCriterium(1000),
                    new ResidualStopCriterium((float)Math.Pow(1.0 / 10.0, iteration)),
                });
                var solver = new GpBiCg(monitor);

                var resultx = solver.Solve(matrixA, vectorb);

                if (!(monitor.Status is CalculationConverged))
                {
                    // Solution was not found, try again downgrading convergence boundary
                    continue;
                }

                Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
                var matrixBReconstruct = matrixA * resultx;

                // Check the reconstruction.
                for (var i = 0; i < order; i++)
                {
                    Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                    Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float)Math.Pow(1.0 / 10.0, iteration - 3));
                }

                return;
            }

            Assert.Fail("Solution was not found in 3 tries");
        }