示例#1
0
        public void TestWriteFuture()
        {
            DefaultWriteFuture future = new DefaultWriteFuture(null);

            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Written);

            TestThread thread = new TestThread(future);

            thread.Start();

            future.Written = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Written);

            future = new DefaultWriteFuture(null);
            thread = new TestThread(future);
            thread.Start();

            future.Exception = new Exception();
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsFalse(future.Written);
            Assert.IsTrue(future.Exception.GetType() == typeof(Exception));
        }
示例#2
0
        public void TestRemoveListener2()
        {
            DefaultCloseFuture future = new DefaultCloseFuture(null);

            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Closed);

            IoFuture f1 = null, f2 = null;
            EventHandler <IoFutureEventArgs> listener1 = (s, e) => f1 = e.Future;
            EventHandler <IoFutureEventArgs> listener2 = (s, e) => f2 = e.Future;

            future.Complete += listener1;
            future.Complete += listener2;
            future.Complete -= listener2;

            TestThread thread = new TestThread(future);

            thread.Start();

            future.Closed = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Closed);

            Assert.AreSame(future, f1);
            Assert.AreSame(null, f2);
        }
示例#3
0
    static void Main()
    {
        Kerfuffle kerf        = new Kerfuffle();
        const int NUM_THREADS = 8;

        Thread[]     threads     = new Thread[NUM_THREADS];
        TestThread[] testThreads = new TestThread[NUM_THREADS];
        // invoke the threads
        for (int i = 0; i < NUM_THREADS; i++)
        {
            testThreads[i] = new TestThread(kerf, i);
            threads[i]     = new Thread(new ThreadStart(testThreads[i].Run));
            threads[i].Start();
        }
        // wait for the threads to finish
        for (int i = 0; i < NUM_THREADS; i++)
        {
            threads[i].Join();
        }
        for (int i = 0; i < NUM_THREADS; i++)
        {
            if (testThreads[i].Failed)
            {
                throw new Exception("Test Failed");
            }
        }
    }
示例#4
0
        public void TestAddListener()
        {
            DefaultCloseFuture future = new DefaultCloseFuture(null);

            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Closed);

            IoFuture f1 = null, f2 = null;

            future.Complete += (s, e) => f1 = e.Future;
            future.Complete += (s, e) => f2 = e.Future;

            TestThread thread = new TestThread(future);

            thread.Start();

            future.Closed = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Closed);

            Assert.AreSame(future, f1);
            Assert.AreSame(future, f2);
        }
示例#5
0
        public TestThread ObtainThread(string name)
        {
            var t = new TestThread(name);

            threads.Add(t);
            return(t);
        }
示例#6
0
 public void ExecuteOn(TestThread t)
 {
     t.Execute(() => {
         executionResult.Result = fun();
         executionResult.MarkAsFinished();
     });
 }
示例#7
0
        public ExecutionResult Execute(TestThread t, Func <object> fun, string name = "unnamed operation")
        {
            var result = new ExecutionResult(this, name);
            var action = Tuple.Create(t, new DelayedAction(fun, result, name));

            action.Item2.ExecuteOn(action.Item1);
            LocalThread.Wait();
            return(result);
        }
示例#8
0
 public void testStaticAction1()
 {
     var testThread = new TestThread();
     testThread.Start();
     Thread.Sleep(1000);
     testThread.Quit();
     AssertNull("Error should be null", testThread.error);
     AssertEquals("Result should be OK", "OK", testThread.result);
 }
示例#9
0
        public void testStaticAction1()
        {
            var testThread = new TestThread();

            testThread.Start();
            Thread.Sleep(1000);
            testThread.Quit();
            AssertNull("Error should be null", testThread.error);
            AssertEquals("Result should be OK", "OK", testThread.result);
        }
示例#10
0
    // Use this for initialization
    void Start()
    {
        ResourceLoadManager.Instance.Initialize();
        Debug.Log(Application.persistentDataPath);

        TestThread tt = gameObject.GetComponent <TestThread>();

        for (int i = 0; i < 10; ++i)
        {
            tt.AddDataReq("TestBundle  " + i, TestCB);
        }
    }
    static void Main()
    {
        // Test the C# types customisation by modifying the default char * typemaps to return a single char
        Things things = new Things();

        System.Text.StringBuilder initialLetters = new System.Text.StringBuilder();
        char myChar = things.start("boo");

        initialLetters.Append(myChar);
        myChar = Things.stop("hiss");
        initialLetters.Append(myChar);
        myChar = csharp_typemaps.partyon("off");
        initialLetters.Append(myChar);
        if (initialLetters.ToString() != "bho")
        {
            throw new Exception("initial letters failed");
        }

        // $csinput expansion
        csharp_typemaps.myInt = 1;
        try {
            csharp_typemaps.myInt = -1;
            throw new Exception("oops");
        } catch (ApplicationException) {
        }

        // Eager garbage collector test
        {
            const int    NUM_THREADS = 8;
            Thread[]     threads     = new Thread[NUM_THREADS];
            TestThread[] testThreads = new TestThread[NUM_THREADS];
            // invoke the threads
            for (int i = 0; i < NUM_THREADS; i++)
            {
                testThreads[i] = new TestThread(i);
                threads[i]     = new Thread(new ThreadStart(testThreads[i].Run));
                threads[i].Start();
            }
            // wait for the threads to finish
            for (int i = 0; i < NUM_THREADS; i++)
            {
                threads[i].Join();
            }
            for (int i = 0; i < NUM_THREADS; i++)
            {
                if (testThreads[i].Failed)
                {
                    throw new Exception("Test Failed");
                }
            }
        }
    }
        // ReSharper disable once UnusedParameter.Local
        private TestThread CreateInsertThread(int mainCounter, ManualResetEvent signal)
        {
            var tt = TestThread.Start(th =>
            {
                for (int i = 0; i < 10; i++)
                {
                    _dict.TryAdd("" + i, "" + i);
                    _added++;
                }
                return(true);
            }, signal);

            return(tt);
        }
示例#13
0
        private bool ExecNext(string msg, int count)
        {
            //--実行権の取得
            this.WriteLine("Borrow");
            TestFunction dlg  = new TestFunction(this.testFunction);
            TestThread   dlg2 = new TestThread(this.Exec_thread);

            dlg2.BeginInvoke(
                dlg, msg, count,
                new System.AsyncCallback(this.Exec_callback),
                new object[] { dlg2, msg }            //←Exec_callback() の ar.AsyncState に入る
                );
            return(true);
        }
        // ReSharper disable once UnusedParameter.Local
        private TestThread CreateRemoveThread(int mainCounter, ManualResetEvent signal)
        {
            var tt = TestThread.Start(th =>
            {
                for (int i = 0; i < 10; i++)
                {
                    _dict.Remove("" + i);
                    _removed++;
                }
                return(true);
            }, signal);

            return(tt);
        }
示例#15
0
        public void TestInitialize()
        {
            shutdown = new Mock <IProvideShutdownSignal>();

            shutdown.SetupGet(s => s.ShouldShutdown)
            .Returns(() => loopCount > 0)
            .Callback(() => loopCount--);

            log = new Mock <ILog>();

            dataAccess = new Mock <IBusDataAccess>();

            testThread = new TestThread("Test", 100, log.Object, dataAccess.Object, shutdown.Object);
        }
        // ReSharper disable once UnusedParameter.Local
        private TestThread CreateReadThread(int mainCounter, ManualResetEvent signal)
        {
            var tt = TestThread.Start(th =>
            {
                var enumerator = _dict.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var result = enumerator.Current;
                    Assert.IsNotNull(result.Key);
                    _read++;
                }
                return(true);
            }, signal);

            return(tt);
        }
示例#17
0
        public void TestCloseFuture()
        {
            DefaultCloseFuture future = new DefaultCloseFuture(null);
            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Closed);

            TestThread thread = new TestThread(future);
            thread.Start();

            future.Closed = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Closed);
        }
示例#18
0
        public void Initialization_DefaultOptions_StartsThreadSuccessfully()
        {
            ThreadManager.Initialise();
            try
            {
                TestThread testThread = new TestThread();
                ThreadManager.ThreadStart(testThread, nameof(testThread), ThreadPriority.Normal);

                Thread.Sleep(1000);
                testThread.CancelThread();
                ThreadManager.CancelAll();
            }
            finally
            {
                ThreadManager.Finalise();
            }
        }
        /*
         * 1. By the user deciding on how many threads to start, the barrier will not break
         *      until that number is shit
         *
         * 2. Same as above, all threads will process when the barrier limit has been reached
         *
         * 3. This is hard to prove, but with the added turnstile one should be able to prove
         *      that with stepping through the code this is valid
         *
         */
        public static void TestOneTwoThree()
        {
            const UInt64 noThreads = 100;

            TestThread[] threads = new TestThread[noThreads];

            Console.WriteLine("Press any key to create a thread:");
            Console.WriteLine("Barrier threshold has been set to: {0}", barrierThreshold);

            for (int i = 0; i < threads.Length; ++i)
            {
                Console.ReadLine();
                threads [i] = new TestThread("#" + i);
                threads [i].Start();
                Console.WriteLine("Thread {0} has been created and started!", i);
            }
        }
示例#20
0
        public void TestConnectFuture()
        {
            DefaultConnectFuture future = new DefaultConnectFuture();

            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Connected);
            Assert.IsNull(future.Session);
            Assert.IsNull(future.Exception);

            TestThread thread = new TestThread(future);

            thread.Start();

            IoSession session = new DummySession();

            future.SetSession(session);
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Connected);
            Assert.AreSame(session, future.Session);
            Assert.IsNull(future.Exception);

            future = new DefaultConnectFuture();
            thread = new TestThread(future);
            thread.Start();
            future.Exception = new IOException();
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsFalse(future.Connected);
            Assert.IsTrue(future.Exception is IOException);

            try
            {
                IoSession s = future.Session;
                Assert.Fail("IOException should be thrown.");
            }
            catch (Exception)
            {
                // Signifies a successful test execution
                Assert.IsTrue(true);
            }
        }
示例#21
0
        public void TestCloseFuture()
        {
            DefaultCloseFuture future = new DefaultCloseFuture(null);

            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Closed);

            TestThread thread = new TestThread(future);

            thread.Start();

            future.Closed = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Closed);
        }
示例#22
0
        public void TestConnectFuture()
        {
            DefaultConnectFuture future = new DefaultConnectFuture();
            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Connected);
            Assert.IsNull(future.Session);
            Assert.IsNull(future.Exception);

            TestThread thread = new TestThread(future);
            thread.Start();

            IoSession session = new DummySession();

            future.SetSession(session);
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Connected);
            Assert.AreSame(session, future.Session);
            Assert.IsNull(future.Exception);

            future = new DefaultConnectFuture();
            thread = new TestThread(future);
            thread.Start();
            future.Exception = new IOException();
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsFalse(future.Connected);
            Assert.IsTrue(future.Exception is IOException);

            try
            {
                IoSession s = future.Session;
                Assert.Fail("IOException should be thrown.");
            }
            catch (Exception)
            {
                // Signifies a successful test execution
                Assert.IsTrue(true);
            }
        }
  static void Main() 
  {
    // Test the C# types customisation by modifying the default char * typemaps to return a single char
    Things things = new Things();
    System.Text.StringBuilder initialLetters = new System.Text.StringBuilder();
    char myChar = things.start("boo");
    initialLetters.Append(myChar);
    myChar = Things.stop("hiss");
    initialLetters.Append(myChar);
    myChar = csharp_typemaps.partyon("off");
    initialLetters.Append(myChar);
    if (initialLetters.ToString() != "bho")
      throw new Exception("initial letters failed");

    // $csinput expansion
    csharp_typemaps.myInt = 1;
    try {
      csharp_typemaps.myInt = -1;
      throw new Exception("oops");
    } catch (ApplicationException) {
    }

    // Eager garbage collector test
    {
      const int NUM_THREADS = 8;
      Thread[] threads = new Thread[NUM_THREADS];
      TestThread[] testThreads = new TestThread[NUM_THREADS];
      // invoke the threads
      for (int i=0; i<NUM_THREADS; i++) {
        testThreads[i] = new TestThread(i);
        threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
        threads[i].Start();
      }
      // wait for the threads to finish
      for (int i=0; i<NUM_THREADS; i++) {
        threads[i].Join();
      }
      for (int i=0; i<NUM_THREADS; i++) {
        if (testThreads[i].Failed) throw new Exception("Test Failed");
      }
    }

  }
示例#24
0
        private void performTest(LoadState expectedState, TestThread thread, bool shouldThrow)
        {
            var container = new BlockableLoadContainer();

            // Load to the expected state
            if (expectedState > LoadState.NotLoaded)
            {
                LoadState stateToWaitFor = expectedState;

                AddStep("begin loading", () =>
                {
                    LoadComponentAsync(container, Add);

                    switch (expectedState)
                    {
                    // Special case for the load thread: the action is invoked after the event is set, so this is handled in the switch below
                    case LoadState.Loading when thread != TestThread.Load:
                        container.LoadingEvent.Set();
                        break;
示例#25
0
        public void ScopesHaveProperTreeStructure()
        {
            // Arrange
            var t      = SetUp();
            var logger = t.Item1;
            var store  = t.Item2;

            var    testThread   = new TestThread(logger);
            Thread workerThread = new Thread(testThread.work);

            // Act
            workerThread.Start();
            using (logger.BeginScope("test2"))
            {
                logger.LogWarning("hello world");
                Thread.Sleep(1000);
                logger.LogCritical("goodbye world");
            }
            workerThread.Join();

            // Assert
            // get the root of the activity for scope "test2"
            var root1 = (store.GetActivities())
                        .Where(a => string.Equals(a.Root.State?.ToString(), "test2"))?
                        .FirstOrDefault()?
                        .Root;

            Assert.NotNull(root1);
            var root2 = (store.GetActivities())
                        .Where(a => string.Equals(a.Root.State?.ToString(), "test12"))?
                        .FirstOrDefault()?
                        .Root;

            Assert.NotNull(root2);

            Assert.Equal(0, root1.Children.Count);
            Assert.Equal(2, root1.Messages.Count);
            Assert.Equal(1, root2.Children.Count);
            Assert.Equal(12, root2.Messages.Count);
            Assert.Equal(0, root2.Children.First().Children.Count);
            Assert.Equal(3, root2.Children.First().Messages.Count);
        }
 static void Main() 
 {
   Kerfuffle kerf = new Kerfuffle();
   const int NUM_THREADS = 8;
   Thread[] threads = new Thread[NUM_THREADS];
   TestThread[] testThreads = new TestThread[NUM_THREADS];
   // invoke the threads
   for (int i=0; i<NUM_THREADS; i++) {
     testThreads[i] = new TestThread(kerf, i);
     threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
     threads[i].Start();
   }
   // wait for the threads to finish
   for (int i=0; i<NUM_THREADS; i++) {
     threads[i].Join();
   }
   for (int i=0; i<NUM_THREADS; i++) {
     if (testThreads[i].Failed) throw new Exception("Test Failed");
   }
 }
        // ReSharper disable once UnusedParameter.Local
        private TestThread CreateValuesKeysThread(int mainCounter, ManualResetEvent signal)
        {
            var tt = TestThread.Start(th =>
            {
                // ReSharper disable once UnusedVariable
                foreach (var value in _dict.Values)
                {
                }
                foreach (var key in _dict.Keys)
                {
                    // ReSharper disable once UnusedVariable
                    var result = _dict.ContainsKey(key);
                    var value  = _dict[key];
                    // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                    _dict[key] = new Random(100).Next(1000).ToString() + value;
                }
                return(true);
            }, signal);

            return(tt);
        }
示例#28
0
        // ReSharper restore UnusedParameter.Local
        // ReSharper disable UnusedParameter.Local
        private static void Main(string[] args)
        {
            var stopwatch = new Stopwatch();
            var stopwatchExternal = new Stopwatch();
            var testThread = new TestThread(stopwatch, "TestThread");

            testThread.RunThread();
            stopwatchExternal.Start();
            while (testThread.Status != RunningStatus.Halted)
            {
                Thread.Sleep(5);
            }
            stopwatchExternal.Stop();
            Console.WriteLine(
                string.Format(
                    "Completed in {0} ms, lifecycle was of {1} ms.",
                    stopwatch.ElapsedMilliseconds,
                    stopwatchExternal.ElapsedMilliseconds));
            //Just to avoid the app closing...
            Console.ReadKey();
        }
示例#29
0
        private void Exec_callback(System.IAsyncResult ar)
        {
            this.WriteLine("Exec_callback: before cast");
            object[]   array = (object[])ar.AsyncState;
            TestThread dlg2  = (TestThread)array[0];
            string     c     = (string)array[1];

            try{
                this.WriteLine("Exec_callback: before EndInvoke");
                dlg2.EndInvoke(ar);
                this.WriteLine("Exec_callback: after EndInvoke");
            }catch (System.Exception e) {
                //DEBUG:
                this.WriteLine("caught Error Invoke:" + e.GetType().ToString() + "\n\t" + e.Message);
                ErrorView view = new ErrorView();
                view.AddException(e);
                view.ShowDialog();
            }
            //--実行権の返上
            this.WriteLine("Return");
            this.completed = true;
        }
示例#30
0
        public void ThreadsHaveSeparateActivityContexts()
        {
            // Arrange
            var t      = SetUp();
            var logger = t.Item1;
            var store  = t.Item2;

            var    testThread   = new TestThread(logger);
            Thread workerThread = new Thread(testThread.work);

            // Act
            workerThread.Start();
            using (logger.BeginScope("test1"))
            {
                logger.LogWarning("hello world");
                Thread.Sleep(1000);
                logger.LogCritical("goodbye world");
            }
            workerThread.Join();

            // Assert
            Assert.Equal(17, (store.GetActivities().SelectMany(a => NodeLogs(a.Root, new List <LogInfo>()))).ToList().Count);
            Assert.Equal(2, store.GetActivities().ToList().Count);
        }
示例#31
0
        public void TestLateAddListener()
        {
            DefaultCloseFuture future = new DefaultCloseFuture(null);
            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Closed);

            TestThread thread = new TestThread(future);
            thread.Start();

            future.Closed = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Closed);

            IoFuture f1 = null;
            future.Complete += (s, e) => f1 = e.Future;
            Assert.AreSame(future, f1);
        }
示例#32
0
        private static TestResult ProcessOneRequest(ICacheProvider provider, Dictionary <int, string> keys, TestThread threadInfo)
        {
            DateTime  now = DateTime.Now;
            string    key = keys[RandomHelper.Instance.Next(threadInfo.StartPosition, threadInfo.EndPosition)];
            Stopwatch sw  = new Stopwatch();

            sw.Start();
            var item = provider.GetItem(key);

            sw.Stop();
            DateTime end = DateTime.Now;

            return(new TestResult()
            {
                ThreadNumber = threadInfo.Name,
                DateTimeStart = now,
                DurationMilliseconds = sw.ElapsedMilliseconds,
                DurationTicks = sw.ElapsedTicks,
                DateTimeEnd = end,
                Receive = item.Length,
                Send = key.Length,
            });
        }
示例#33
0
    static void Main()
    {
        // %exception tests
        try {
            csharp_exceptions.ThrowByValue();
            throw new Exception("ThrowByValue not working");
        } catch (DivideByZeroException) {
        }
        try {
            csharp_exceptions.ThrowByReference();
            throw new Exception("ThrowByReference not working");
        } catch (DivideByZeroException) {
        }

        // %csnothrowexception
        csharp_exceptions.NoThrowException();
        csharp_exceptions.NullReference(new Ex("should not throw"));

        // exception specifications
        bool testFailed = false;

        try {
            csharp_exceptions.ExceptionSpecificationValue();
            testFailed = true;
        } catch (ApplicationException) {
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationValue not working");
        }
        try {
            csharp_exceptions.ExceptionSpecificationReference();
            testFailed = true;
        } catch (ApplicationException) {
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationReference not working");
        }
        try {
            csharp_exceptions.ExceptionSpecificationString();
            testFailed = true;
        } catch (ApplicationException e) {
            if (e.Message != "ExceptionSpecificationString")
            {
                throw new Exception("ExceptionSpecificationString unexpected message: " + e.Message);
            }
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationString not working");
        }
        try {
            csharp_exceptions.ExceptionSpecificationInteger();
            testFailed = true;
        } catch (ApplicationException) {
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationInteger not working");
        }

        // null reference exceptions
        try {
            csharp_exceptions.NullReference(null);
            throw new Exception("NullReference not working");
        } catch (ArgumentNullException) {
        }
        try {
            csharp_exceptions.NullValue(null);
            throw new Exception("NullValue not working");
        } catch (ArgumentNullException) {
        }

        // enums
        try {
            csharp_exceptions.ExceptionSpecificationEnumValue();
            testFailed = true;
        } catch (ApplicationException) {
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationEnumValue not working");
        }
        try {
            csharp_exceptions.ExceptionSpecificationEnumReference();
            testFailed = true;
        } catch (ApplicationException) {
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationEnumReference not working");
        }

        // std::string
        try {
            csharp_exceptions.NullStdStringValue(null);
            throw new Exception("NullStdStringValue not working");
        } catch (ArgumentNullException) {
        }
        try {
            csharp_exceptions.NullStdStringReference(null);
            throw new Exception("NullStdStringReference not working");
        } catch (ArgumentNullException) {
        }
        try {
            csharp_exceptions.ExceptionSpecificationStdStringValue();
            testFailed = true;
        } catch (ApplicationException e) {
            if (e.Message != "ExceptionSpecificationStdStringValue")
            {
                throw new Exception("ExceptionSpecificationStdStringValue unexpected message: " + e.Message);
            }
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationStdStringValue not working");
        }
        try {
            csharp_exceptions.ExceptionSpecificationStdStringReference();
            testFailed = true;
        } catch (ApplicationException e) {
            if (e.Message != "ExceptionSpecificationStdStringReference")
            {
                throw new Exception("ExceptionSpecificationStdStringReference unexpected message: " + e.Message);
            }
        }
        if (testFailed)
        {
            throw new Exception("ExceptionSpecificationStdStringReference not working");
        }

        // Memory leak check (The C++ exception stack was never unwound in the original approach to throwing exceptions from unmanaged code)
        try {
            csharp_exceptions.MemoryLeakCheck();
            throw new Exception("MemoryLeakCheck not working");
        } catch (DivideByZeroException) {
        }
        if (Counter.count != 0)
        {
            throw new Exception("Memory leaks when throwing exception. count: " + Counter.count);
        }

        // test exception pending in the csconstruct typemap
        try {
            new constructor(null);
            throw new Exception("constructor 1 not working");
        } catch (ArgumentNullException) {
        }
        try {
            new constructor();
            throw new Exception("constructor 2 not working");
        } catch (ApplicationException) {
        }

        // test exception pending in the csout typemaps
        try {
            csharp_exceptions.ushorttest();
            throw new Exception("csout not working");
        } catch (IndexOutOfRangeException) {
        }

        // test exception pending in the csvarout/csvarin typemaps and canthrow attribute in unmanaged code typemaps (1) global variables
        // 1) global variables
        int numberout = 0;

        try {
            csharp_exceptions.numberin = -1;
            throw new Exception("global csvarin not working");
        } catch (IndexOutOfRangeException) {
        }
        csharp_exceptions.numberin = 5;
        if (csharp_exceptions.numberin != 5)
        {
            throw new Exception("global numberin not 5");
        }
        csharp_exceptions.numberout = 20;
        try {
            numberout += csharp_exceptions.numberout;
            throw new Exception("global csvarout not working");
        } catch (IndexOutOfRangeException) {
        }
        // 2) static member variables
        try {
            InOutStruct.staticnumberin = -1;
            throw new Exception("static csvarin not working");
        } catch (IndexOutOfRangeException) {
        }
        InOutStruct.staticnumberin = 5;
        if (InOutStruct.staticnumberin != 5)
        {
            throw new Exception("static staticnumberin not 5");
        }
        InOutStruct.staticnumberout = 20;
        try {
            numberout += InOutStruct.staticnumberout;
            throw new Exception("static csvarout not working");
        } catch (IndexOutOfRangeException) {
        }
        // 3) member variables
        InOutStruct io = new InOutStruct();

        try {
            io.numberin = -1;
            throw new Exception("member csvarin not working");
        } catch (IndexOutOfRangeException) {
        }
        io.numberin = 5;
        if (io.numberin != 5)
        {
            throw new Exception("member numberin not 5");
        }
        io.numberout = 20;
        try {
            numberout += io.numberout;
            throw new Exception("member csvarout not working");
        } catch (IndexOutOfRangeException) {
        }
        // test SWIG_exception macro - it must return from unmanaged code without executing any further unmanaged code
        try {
            csharp_exceptions.exceptionmacrotest(-1);
            throw new Exception("exception macro not working");
        } catch (IndexOutOfRangeException) {
        }
        if (csharp_exceptions.exception_macro_run_flag)
        {
            throw new Exception("exceptionmacrotest was executed");
        }

        // test all the types of exceptions
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedApplicationException);
            throw new Exception("ApplicationException not caught");
        } catch (ApplicationException e) {
            if (e.Message != "msg")
            {
                throw new Exception("ApplicationException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArithmeticException);
            throw new Exception("ArithmeticException not caught");
        } catch (ArithmeticException e) {
            if (e.Message != "msg")
            {
                throw new Exception("ArithmeticException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedDivideByZeroException);
            throw new Exception("DivideByZeroException not caught");
        } catch (DivideByZeroException e) {
            if (e.Message != "msg")
            {
                throw new Exception("DivideByZeroException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIndexOutOfRangeException);
            throw new Exception("IndexOutOfRangeException not caught");
        } catch (IndexOutOfRangeException e) {
            if (e.Message != "msg")
            {
                throw new Exception("IndexOutOfRangeException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedInvalidOperationException);
            throw new Exception("InvalidOperationException not caught");
        } catch (InvalidOperationException e) {
            if (e.Message != "msg")
            {
                throw new Exception("InvalidOperationException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIOException);
            throw new Exception("IOException not caught");
        } catch (System.IO.IOException e) {
            if (e.Message != "msg")
            {
                throw new Exception("IOException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedNullReferenceException);
            throw new Exception("NullReferenceException not caught");
        } catch (NullReferenceException e) {
            if (e.Message != "msg")
            {
                throw new Exception("NullReferenceException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOutOfMemoryException);
            throw new Exception("OutOfMemoryException not caught");
        } catch (OutOfMemoryException e) {
            if (e.Message != "msg")
            {
                throw new Exception("OutOfMemoryException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOverflowException);
            throw new Exception("OverflowException not caught");
        } catch (OverflowException e) {
            if (e.Message != "msg")
            {
                throw new Exception("OverflowException msg incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedSystemException);
            throw new Exception("SystemException not caught");
        } catch (SystemException e) {
            if (e.Message != "msg")
            {
                throw new Exception("SystemException msg incorrect");
            }
        }

        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentException);
            throw new Exception("ArgumentException not caught");
        } catch (ArgumentException e) {
            if (e.Message.Replace(CRLF, "\n") != "msg\nParameter name: parm")
            {
                throw new Exception("ArgumentException msg incorrect");
            }
            if (e.ParamName != "parm")
            {
                throw new Exception("ArgumentException parm incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentNullException);
            throw new Exception("ArgumentNullException not caught");
        } catch (ArgumentNullException e) {
            if (e.Message.Replace(CRLF, "\n") != "msg\nParameter name: parm")
            {
                throw new Exception("ArgumentNullException msg incorrect");
            }
            if (e.ParamName != "parm")
            {
                throw new Exception("ArgumentNullException parm incorrect");
            }
        }
        try {
            csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentOutOfRangeException);
            throw new Exception("ArgumentOutOfRangeException not caught");
        } catch (ArgumentOutOfRangeException e) {
            if (e.Message.Replace(CRLF, "\n") != "msg\nParameter name: parm")
            {
                throw new Exception("ArgumentOutOfRangeException msg incorrect");
            }
            if (e.ParamName != "parm")
            {
                throw new Exception("ArgumentOutOfRangeException parm incorrect");
            }
        }


        // exceptions in multiple threads test
        {
            ThrowsClass  throwsClass = new ThrowsClass(1234.5678);
            const int    NUM_THREADS = 8;
            Thread[]     threads     = new Thread[NUM_THREADS];
            TestThread[] testThreads = new TestThread[NUM_THREADS];
            // invoke the threads
            for (int i = 0; i < NUM_THREADS; i++)
            {
                testThreads[i] = new TestThread(throwsClass, i);
                threads[i]     = new Thread(new ThreadStart(testThreads[i].Run));
                threads[i].Start();
            }
            // wait for the threads to finish
            for (int i = 0; i < NUM_THREADS; i++)
            {
                threads[i].Join();
            }
            for (int i = 0; i < NUM_THREADS; i++)
            {
                if (testThreads[i].Failed)
                {
                    throw new Exception("Test Failed");
                }
            }
        }


        // test inner exceptions
        try {
            csharp_exceptions.InnerExceptionTest();
            throw new Exception("InnerExceptionTest exception not caught");
        } catch (InvalidOperationException e) {
            if (e.Message != "My OuterException message")
            {
                throw new Exception("OuterException msg incorrect");
            }
            if (e.InnerException.Message != "My InnerException message")
            {
                throw new Exception("InnerException msg incorrect");
            }
        }
    }
示例#34
0
        public void ThreadsHaveSeparateActivityContexts()
        {
            // Arrange
            var t = SetUp();
            var logger = t.Item1;
            var store = t.Item2;

            var testThread = new TestThread(logger);
            Thread workerThread = new Thread(testThread.work);

            // Act
            workerThread.Start();
            using (logger.BeginScope("test1"))
            {
                logger.LogWarning("hello world");
                Thread.Sleep(1000);
                logger.LogCritical("goodbye world");
            }
            workerThread.Join();

            // Assert
            Assert.Equal(17, (store.GetActivities().SelectMany(a => NodeLogs(a.Root, new List<LogInfo>()))).ToList().Count);
            Assert.Equal(2, store.GetActivities().ToList().Count);
        }
示例#35
0
 public void TestLoadedAdd(TestThread thread, bool shouldThrow) => performTest(LoadState.Loaded, thread, shouldThrow);
示例#36
0
 static void StartThread(int mSec, int id, bool IsBackground)
 {
     TestThread
         TestThread = new TestThread(mSec, id.ToString(), IsBackground);
 }
 private void TestTerms(Fields fieldsSource, ISet<Option> options, FieldInfo.IndexOptions maxTestOptions, FieldInfo.IndexOptions maxIndexOptions, bool alwaysTestMax)
 {
     if (options.Contains(Option.THREADS))
     {
         int numThreads = TestUtil.NextInt(Random(), 2, 5);
         ThreadClass[] threads = new ThreadClass[numThreads];
         for (int threadUpto = 0; threadUpto < numThreads; threadUpto++)
         {
             threads[threadUpto] = new TestThread(this, fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax);
             threads[threadUpto].Start();
         }
         for (int threadUpto = 0; threadUpto < numThreads; threadUpto++)
         {
             threads[threadUpto].Join();
         }
     }
     else
     {
         TestTermsOneThread(fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax);
     }
 }
示例#38
0
        public void TestWriteFuture()
        {
            DefaultWriteFuture future = new DefaultWriteFuture(null);
            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Written);

            TestThread thread = new TestThread(future);
            thread.Start();

            future.Written = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Written);

            future = new DefaultWriteFuture(null);
            thread = new TestThread(future);
            thread.Start();

            future.Exception = new Exception();
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsFalse(future.Written);
            Assert.IsTrue(future.Exception.GetType() == typeof(Exception));
        }
示例#39
0
 public ThreadSyncTester()
 {
     threads     = new List <TestThread>();
     LocalThread = new TestThread("local");
 }
示例#40
0
        public void TestRemoveListener2()
        {
            DefaultCloseFuture future = new DefaultCloseFuture(null);
            Assert.IsFalse(future.Done);
            Assert.IsFalse(future.Closed);

            IoFuture f1 = null, f2 = null;
            EventHandler<IoFutureEventArgs> listener1 = (s, e) => f1 = e.Future;
            EventHandler<IoFutureEventArgs> listener2 = (s, e) => f2 = e.Future;

            future.Complete += listener1;
            future.Complete += listener2;
            future.Complete -= listener2;

            TestThread thread = new TestThread(future);
            thread.Start();

            future.Closed = true;
            thread.Join();

            Assert.IsTrue(thread.success);
            Assert.IsTrue(future.Done);
            Assert.IsTrue(future.Closed);

            Assert.AreSame(future, f1);
            Assert.AreSame(null, f2);
        }
    public static string CRLF = "\r\n"; // Some CLR implementations use a CRLF instead of just CR

    #endregion Fields

    #region Methods

    static void Main()
    {
        // %exception tests
          try {
        csharp_exceptions.ThrowByValue();
        throw new Exception("ThrowByValue not working");
          } catch (DivideByZeroException) {
          }
          try {
        csharp_exceptions.ThrowByReference();
        throw new Exception("ThrowByReference not working");
          } catch (DivideByZeroException) {
          }

          // %csnothrowexception
          csharp_exceptions.NoThrowException();
          csharp_exceptions.NullReference(new Ex("should not throw"));

          // exception specifications
          bool testFailed = false;
          try {
        csharp_exceptions.ExceptionSpecificationValue();
        testFailed = true;
          } catch (ApplicationException) {
          }
          if (testFailed) throw new Exception("ExceptionSpecificationValue not working");
          try {
        csharp_exceptions.ExceptionSpecificationReference();
        testFailed = true;
          } catch (ApplicationException) {
          }
          if (testFailed) throw new Exception("ExceptionSpecificationReference not working");
          try {
        csharp_exceptions.ExceptionSpecificationString();
        testFailed = true;
          } catch (ApplicationException e) {
        if (e.Message != "ExceptionSpecificationString") throw new Exception("ExceptionSpecificationString unexpected message: " + e.Message);
          }
          if (testFailed) throw new Exception("ExceptionSpecificationString not working");
          try {
        csharp_exceptions.ExceptionSpecificationInteger();
        testFailed = true;
          } catch (ApplicationException) {
          }
          if (testFailed) throw new Exception("ExceptionSpecificationInteger not working");

          // null reference exceptions
          try {
        csharp_exceptions.NullReference(null);
        throw new Exception("NullReference not working");
          } catch (ArgumentNullException) {
          }
          try {
        csharp_exceptions.NullValue(null);
        throw new Exception("NullValue not working");
          } catch (ArgumentNullException) {
          }

          // enums
          try {
        csharp_exceptions.ExceptionSpecificationEnumValue();
        testFailed = true;
          } catch (ApplicationException) {
          }
          if (testFailed) throw new Exception("ExceptionSpecificationEnumValue not working");
          try {
        csharp_exceptions.ExceptionSpecificationEnumReference();
        testFailed = true;
          } catch (ApplicationException) {
          }
          if (testFailed) throw new Exception("ExceptionSpecificationEnumReference not working");

          // std::string
          try {
        csharp_exceptions.NullStdStringValue(null);
        throw new Exception("NullStdStringValue not working");
          } catch (ArgumentNullException) {
          }
          try {
        csharp_exceptions.NullStdStringReference(null);
        throw new Exception("NullStdStringReference not working");
          } catch (ArgumentNullException) {
          }
          try {
        csharp_exceptions.ExceptionSpecificationStdStringValue();
        testFailed = true;
          } catch (ApplicationException e) {
        if (e.Message != "ExceptionSpecificationStdStringValue") throw new Exception("ExceptionSpecificationStdStringValue unexpected message: " + e.Message);
          }
          if (testFailed) throw new Exception("ExceptionSpecificationStdStringValue not working");
          try {
        csharp_exceptions.ExceptionSpecificationStdStringReference();
        testFailed = true;
          } catch (ApplicationException e) {
        if (e.Message != "ExceptionSpecificationStdStringReference") throw new Exception("ExceptionSpecificationStdStringReference unexpected message: " + e.Message);
          }
          if (testFailed) throw new Exception("ExceptionSpecificationStdStringReference not working");

          // Memory leak check (The C++ exception stack was never unwound in the original approach to throwing exceptions from unmanaged code)
          try {
        csharp_exceptions.MemoryLeakCheck();
        throw new Exception("MemoryLeakCheck not working");
          } catch (DivideByZeroException) {
          }
          if (Counter.count != 0) throw new Exception("Memory leaks when throwing exception. count: " + Counter.count);

          // test exception pending in the csconstruct typemap
          try {
        new constructor(null);
        throw new Exception("constructor 1 not working");
          } catch (ArgumentNullException) {
          }
          try {
        new constructor();
        throw new Exception("constructor 2 not working");
          } catch (ApplicationException) {
          }

          // test exception pending in the csout typemaps
          try {
        csharp_exceptions.ushorttest();
        throw new Exception("csout not working");
          } catch (IndexOutOfRangeException) {
          }

          // test exception pending in the csvarout/csvarin typemaps and canthrow attribute in unmanaged code typemaps (1) global variables
          // 1) global variables
          int numberout = 0;
          try {
        csharp_exceptions.numberin = -1;
        throw new Exception("global csvarin not working");
          } catch (IndexOutOfRangeException) {
          }
          csharp_exceptions.numberin = 5;
          if (csharp_exceptions.numberin != 5)
        throw new Exception("global numberin not 5");
          csharp_exceptions.numberout = 20;
          try {
        numberout += csharp_exceptions.numberout;
        throw new Exception("global csvarout not working");
          } catch (IndexOutOfRangeException) {
          }
          // 2) static member variables
          try {
        InOutStruct.staticnumberin = -1;
        throw new Exception("static csvarin not working");
          } catch (IndexOutOfRangeException) {
          }
          InOutStruct.staticnumberin = 5;
          if (InOutStruct.staticnumberin != 5)
        throw new Exception("static staticnumberin not 5");
          InOutStruct.staticnumberout = 20;
          try {
        numberout += InOutStruct.staticnumberout;
        throw new Exception("static csvarout not working");
          } catch (IndexOutOfRangeException) {
          }
          // 3) member variables
          InOutStruct io = new InOutStruct();
          try {
        io.numberin = -1;
        throw new Exception("member csvarin not working");
          } catch (IndexOutOfRangeException) {
          }
          io.numberin = 5;
          if (io.numberin != 5)
        throw new Exception("member numberin not 5");
          io.numberout = 20;
          try {
        numberout += io.numberout;
        throw new Exception("member csvarout not working");
          } catch (IndexOutOfRangeException) {
          }
          // test SWIG_exception macro - it must return from unmanaged code without executing any further unmanaged code
          try {
        csharp_exceptions.exceptionmacrotest(-1);
        throw new Exception("exception macro not working");
          } catch (IndexOutOfRangeException) {
          }
          if (csharp_exceptions.exception_macro_run_flag)
        throw new Exception("exceptionmacrotest was executed");

          // test all the types of exceptions
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedApplicationException);
        throw new Exception("ApplicationException not caught");
          } catch (ApplicationException e) {
        if (e.Message != "msg") throw new Exception("ApplicationException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArithmeticException);
        throw new Exception("ArithmeticException not caught");
          } catch (ArithmeticException e) {
        if (e.Message != "msg") throw new Exception("ArithmeticException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedDivideByZeroException);
        throw new Exception("DivideByZeroException not caught");
          } catch (DivideByZeroException e) {
        if (e.Message != "msg") throw new Exception("DivideByZeroException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIndexOutOfRangeException);
        throw new Exception("IndexOutOfRangeException not caught");
          } catch (IndexOutOfRangeException e) {
        if (e.Message != "msg") throw new Exception("IndexOutOfRangeException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedInvalidOperationException);
        throw new Exception("InvalidOperationException not caught");
          } catch (InvalidOperationException e) {
        if (e.Message != "msg") throw new Exception("InvalidOperationException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedIOException);
        throw new Exception("IOException not caught");
          } catch (System.IO.IOException e) {
        if (e.Message != "msg") throw new Exception("IOException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedNullReferenceException);
        throw new Exception("NullReferenceException not caught");
          } catch (NullReferenceException e) {
        if (e.Message != "msg") throw new Exception("NullReferenceException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOutOfMemoryException);
        throw new Exception("OutOfMemoryException not caught");
          } catch (OutOfMemoryException e) {
        if (e.Message != "msg") throw new Exception("OutOfMemoryException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedOverflowException);
        throw new Exception("OverflowException not caught");
          } catch (OverflowException e) {
        if (e.Message != "msg") throw new Exception("OverflowException msg incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedSystemException);
        throw new Exception("SystemException not caught");
          } catch (SystemException e) {
        if (e.Message != "msg") throw new Exception("SystemException msg incorrect");
          }

          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentException);
        throw new Exception("ArgumentException not caught");
          } catch (ArgumentException e) {
        if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentException msg incorrect");
        if (e.ParamName != "parm") throw new Exception("ArgumentException parm incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentNullException);
        throw new Exception("ArgumentNullException not caught");
          } catch (ArgumentNullException e) {
        if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentNullException msg incorrect");
        if (e.ParamName != "parm") throw new Exception("ArgumentNullException parm incorrect");
          }
          try {
        csharp_exceptions.check_exception(UnmanagedExceptions.UnmanagedArgumentOutOfRangeException);
        throw new Exception("ArgumentOutOfRangeException not caught");
          } catch (ArgumentOutOfRangeException e) {
        if (e.Message.Replace(CRLF,"\n") != "msg\nParameter name: parm") throw new Exception("ArgumentOutOfRangeException msg incorrect");
        if (e.ParamName != "parm") throw new Exception("ArgumentOutOfRangeException parm incorrect");
          }

          // exceptions in multiple threads test
          {
        ThrowsClass throwsClass = new ThrowsClass(1234.5678);
        const int NUM_THREADS = 8;
        Thread[] threads = new Thread[NUM_THREADS];
        TestThread[] testThreads = new TestThread[NUM_THREADS];
        // invoke the threads
        for (int i=0; i<NUM_THREADS; i++) {
            testThreads[i] = new TestThread(throwsClass, i);
            threads[i] = new Thread(new ThreadStart(testThreads[i].Run));
            threads[i].Start();
        }
        // wait for the threads to finish
        for (int i=0; i<NUM_THREADS; i++) {
            threads[i].Join();
        }
        for (int i=0; i<NUM_THREADS; i++) {
            if (testThreads[i].Failed) throw new Exception("Test Failed");
        }
          }

          // test inner exceptions
          try {
        csharp_exceptions.InnerExceptionTest();
        throw new Exception("InnerExceptionTest exception not caught");
          } catch (InvalidOperationException e) {
        if (e.Message != "My OuterException message") throw new Exception("OuterException msg incorrect");
        if (e.InnerException.Message != "My InnerException message") throw new Exception("InnerException msg incorrect");
          }
    }
示例#42
0
文件: Program.cs 项目: undici77/CsLog
    static void Main(string[] args)
    {
        TestThread test_thread;
        int        id;

        // Set process timers granularity to 1ms
        TimeBeginPeriod(1);

        // Initialize log
        Log.Instance.Init("./", "log", Append);

        // Set log level to init value (INFO_LEVEL + DEBUG_LEVEL + CATCH_LEVEL)
        Log.Instance.Level = 7;

        // Enable log to file
        Log.Instance.ToFile = true;

        // Write some init log
        Log.Instance.Info("Main: started");
        Log.Instance.Debug("Main: Wait 100 ms and start asynch test thread");

        Thread.Sleep(100);

        // Create test thread that will write some async log
        test_thread = new TestThread();

        // Write some debug log
        for (id = 0; id < 20; id++)
        {
            Log.Instance.Debug("Main: write some debug [" + id + "]");
            Thread.Sleep(10);
        }

        Log.Instance.Info("Main: let's try to log a catch exception");
        try
        {
            Log.Instance.Info("Main: creating a null string and trying to access to it");

            string str = null;
            str = str.Substring(0);

            Log.Instance.Error("Main: if you see this line in log, something gone wrong");
        }
        catch (Exception ex)
        {
            Log.Instance.Catch("Main: " + ex.Message);
        }

        // Wait test thread end
        test_thread.Join();

        // Let's disable now log to file
        Log.Instance.Info("Main: Let's disable now log to file");

        // ToFile is ASYNCRONOUS!!
        Thread.Sleep(10);
        Log.Instance.ToFile = false;
        Thread.Sleep(10);

        Log.Instance.Error("Main: this message will not appear in log file");
        Thread.Sleep(10);

        // Let's enable now log to file
        Log.Instance.ToFile = true;
        // ToFile is ASYNCRONOUS!!
        Thread.Sleep(10);
        Log.Instance.Info("Main: Let's enable again log to file");

        // ToFile is ASYNCRONOUS!!
        Thread.Sleep(10);

        Log.Instance.Info("Main: end");

        // Close log
        Log.Instance.End();

        Console.WriteLine("... Press any key to close window ...");
        Console.ReadKey();
    }
示例#43
0
        public void ScopesHaveProperTreeStructure()
        {
            // Arrange
            var t = SetUp();
            var logger = t.Item1;
            var store = t.Item2;

            var testThread = new TestThread(logger);
            Thread workerThread = new Thread(testThread.work);

            // Act
            workerThread.Start();
            using (logger.BeginScope("test2"))
            {
                logger.LogWarning("hello world");
                Thread.Sleep(1000);
                logger.LogCritical("goodbye world");
            }
            workerThread.Join();

            // Assert
            // get the root of the activity for scope "test2"
            var root1 = (store.GetActivities())
                .Where(a => string.Equals(a.Root.State?.ToString(), "test2"))?
                .FirstOrDefault()?
                .Root;
            Assert.NotNull(root1);
            var root2 = (store.GetActivities())
                .Where(a => string.Equals(a.Root.State?.ToString(), "test12"))?
                .FirstOrDefault()?
                .Root;
            Assert.NotNull(root2);

            Assert.Equal(0, root1.Children.Count);
            Assert.Equal(2, root1.Messages.Count);
            Assert.Equal(1, root2.Children.Count);
            Assert.Equal(12, root2.Messages.Count);
            Assert.Equal(0, root2.Children.First().Children.Count);
            Assert.Equal(3, root2.Children.First().Messages.Count);
        }