public void ReturnsTrueOnSuccessfulDisposal()
 {
     var disposable = new Disposable();
     var result = disposable.DisposeSafely();
     Assert.IsTrue(result);
     Assert.IsTrue(disposable.DisposeWasCalled);
 }
Пример #2
0
        public void ObjectPoolTestFactory()
        {
            var factory1 = new Disposable();
            var factory2 = new Disposable();
            var objectPool = new ObjectPool<Disposable, Disposable>();

            objectPool.UpdateFactory(ObjectFactory.Create(factory1, d => d.Create()));
            var p3 = objectPool.GetOrCreate();
            p3.Dispose();

            objectPool.UpdateFactory(ObjectFactory.Create(factory2, d => d.Create()));
            Assert.IsTrue(factory1.Disposed);

            var p1 = objectPool.GetOrCreate();
            var p2 = objectPool.GetOrCreate();

            p1.Dispose();
            p2.Dispose();

            p1 = objectPool.GetOrCreate();
            p1.Dispose();

            objectPool.Dispose();

            factory1.AssertChildrenDisposed();
            Assert.AreEqual(1, factory1.Children.Count);

            factory2.AssertChildrenDisposed();
            Assert.AreEqual(2, factory2.Children.Count);

            Assert.IsTrue(factory2.Disposed);
        }
Пример #3
0
 public ImageReader(Disposable<Stream> stream, string file_name)
     : base(stream.value)
 {
     image = new Image ();
     image.Stream = stream;
     image.FileName = file_name;
 }
Пример #4
0
 public static ImageWriter CreateDebugWriter(ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
 {
     var writer = new ImageWriter (module, "PDB V1.0", metadata, stream, metadataOnly: true);
     var length = metadata.text_map.GetLength ();
     writer.text = new Section { SizeOfRawData = length, VirtualSize = length };
     return writer;
 }
Пример #5
0
        public void should_return_true_and_instance_should_not_be_null_if_provided_type_can_be_resolved()
        {
            var container = new Container();

            object o;
            container.TryGet(typeof(object), out o).ShouldBe(true);
            o.ShouldNotBe(null);

            container.TryGet(out o).ShouldBe(true);
            o.ShouldNotBe(null);

            container.Configure(x => x.For<IDisposable>().Use<Disposable>());

            container.TryGet(typeof(IDisposable), out o).ShouldBe(true);
            o.ShouldNotBe(null);

            IDisposable disposable;
            container.TryGet(out disposable).ShouldBe(true);
            disposable.ShouldNotBe(null);

            var namedDisposable = new Disposable();
            container.Configure(x => x.For<IDisposable>("xyz").Use(namedDisposable));

            TestClassWithDisposable testClassWithDisposable;
            container.TryGet(out testClassWithDisposable).ShouldBe(true);
            testClassWithDisposable.ShouldNotBe(null);
            testClassWithDisposable.Disposable.ShouldNotBe(namedDisposable);

            container.TryGet("xyz", out testClassWithDisposable).ShouldBe(true);
            testClassWithDisposable.ShouldNotBe(null);
            testClassWithDisposable.Disposable.ShouldBe(namedDisposable);
        }
 public void InvokesErrorHandlerOnExceptionDuringDispose()
 {
     var errorHandlerWasInvoked = false;
     var disposable = new Disposable(throwException: true);
     var result = disposable.DisposeSafely(error => errorHandlerWasInvoked = true);
     Assert.IsFalse(result);
     Assert.IsTrue(errorHandlerWasInvoked);
     Assert.IsTrue(disposable.DisposeWasCalled);
 }
Пример #7
0
 public static Image ReadImage(Disposable<Stream> stream, string file_name)
 {
     try {
         var reader = new ImageReader (stream, file_name);
         reader.ReadImage ();
         return reader.image;
     } catch (EndOfStreamException e) {
         throw new BadImageFormatException (stream.value.GetFileName (), e);
     }
 }
Пример #8
0
 public void NormalTest()
 {
     using (var disposable = new Disposable())
     using (var disposableGuard = ScopeGuard.Create(disposable))
     {
         AssertNotDisposed(disposable, disposableGuard);
         disposableGuard.Dismiss();
         AssertNotDisposed(disposable, disposableGuard);
         disposableGuard.Dispose();
         AssertNotDisposed(disposable, disposableGuard);
     }
 }
Пример #9
0
        public void ObjectPoolTestConcurrency()
        {
            var factories = new List<Disposable> { new Disposable() };
            var objectPool = new ObjectPool<Disposable, Disposable>(ObjectFactory.Create(factories[0], d => d.Create()));

            var t1 = new Thread(() =>
            {
                for (int i = 0; i < 500; i++)
                {
                    var p = objectPool.GetOrCreate();
                    Thread.Sleep(5);
                    p.Dispose();
                }
            });

            var t2 = new Thread(() =>
            {
                for (int i = 0; i < 500; i++)
                {
                    var p = objectPool.GetOrCreate();
                    Thread.Sleep(7);
                    p.Dispose();
                }
            });

            var t3 = new Thread(() =>
            {
                for (int i = 0; i < 20; i++)
                {
                    var f = new Disposable();
                    objectPool.UpdateFactory(ObjectFactory.Create(f, d => d.Create()));
                    Thread.Sleep(20);
                }
            });

            t1.Start();
            t2.Start();
            t3.Start();

            t1.Join();
            t2.Join();
            t3.Join();

            objectPool.Dispose();

            foreach (var f in factories)
            {
                Assert.IsTrue(f.Disposed);

                f.AssertChildrenDisposed();
            }
        }
		public void CheckFreeze()
		{
			var sut = new Disposable();
			sut.Dispose();
			Assert.Equal( 1, sut.Count );
			sut.Dispose();
			Assert.Equal( 1, sut.Count );

			sut.Other();
			Assert.Equal( 2, sut.Count );
			sut.Other();
			Assert.Equal( 2, sut.Count );
		}
Пример #11
0
 public void FailureTest()
 {
     using (var disposable = new Disposable())
     {
         ScopeGuard<Disposable> disposableGuard = ScopeGuard.Create(disposable);
         disposableGuard.Dispose();
         Assert.IsTrue(disposable.DisposeCalled);
         AssertThrow<ObjectDisposedException>(delegate { disposableGuard.Resource.Ignore(); });
         disposableGuard.Dispose();
         AssertThrow<ObjectDisposedException>(delegate { disposableGuard.Resource.Ignore(); });
         AssertThrow<ObjectDisposedException>(delegate { disposableGuard.Dismiss(); });
     }
 }
        public void InstanceRegisteredWith_SingleInstance_IsNotDisposedOnScopeDisposal()
        {
            var disposable = new Disposable();
            _container.RegisterInstance<Disposable>(disposable);
            var activator = CreateActivator();

            using (var scope = activator.BeginScope())
            {
                var instance = scope.Resolve(typeof(Disposable));
                Assert.IsFalse(disposable.Disposed);
            }

            Assert.IsFalse(disposable.Disposed);
        }
        public void InstanceRegisteredWith_InstancePerDependency_IsDisposedOnScopeDisposal()
        {
            var disposable = new Disposable();
            _builder.Register(c => disposable).InstancePerDependency();
            var activator = CreateActivator();

            using (var scope = activator.BeginScope())
            {
                var instance = scope.Resolve(typeof(Disposable));
                Assert.IsFalse(disposable.Disposed);
            }

            Assert.IsTrue(disposable.Disposed);
        }
        public void InstanceRegisteredWith_SingletonScope_IsNotDisposedOnScopeDisposal()
        {
            var disposable = new Disposable();
            _kernel.Bind<Disposable>().ToMethod(c => disposable).InSingletonScope();
            var activator = CreateActivator();

            using (var scope = activator.BeginScope())
            {
                var instance = scope.Resolve(typeof(Disposable));
                Assert.IsFalse(disposable.Disposed);
            }

            Assert.IsFalse(disposable.Disposed);
        }
Пример #15
0
        public void ObjectPoolTestDangling()
        {
            var factory = new Disposable();
            var objectPool = new ObjectPool<Disposable, Disposable>(ObjectFactory.Create(factory, d => d.Create()));
            var p1 = objectPool.GetOrCreate();
            objectPool.Dispose();

            Assert.IsTrue(factory.Disposed);
            Assert.AreEqual(1, factory.Children.Count);

            Assert.IsFalse(factory.Children[0].Disposed);

            // don't throw exception if we return pool too late
            p1.Dispose();
        }
Пример #16
0
        public void ScopedInstanceDisposesIDisposables()
        {
            var disposable = new Disposable();
			
            // Arrange
            var scopedInstance = new ScopedInstance<Disposable>
            {
                Value = disposable,
            };
			
            // Act
            scopedInstance.Dispose();
			
            // Assert
            Assert.True(disposable.IsDisposed);
        }
Пример #17
0
        ImageWriter(ModuleDefinition module, string runtime_version, MetadataBuilder metadata, Disposable<Stream> stream, bool metadataOnly = false)
            : base(stream.value)
        {
            this.module = module;
            this.runtime_version = runtime_version;
            this.text_map = metadata.text_map;
            this.stream = stream;
            this.metadata = metadata;
            if (metadataOnly)
                return;

            this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64;
            this.has_reloc = module.Architecture == TargetArchitecture.I386;
            this.GetDebugHeader ();
            this.GetWin32Resources ();
            this.BuildTextMap ();
            this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc?
        }
        public void TestUsing1_CanceledResource_CanceledBody_Disposable()
        {
            bool executed = false;
            Disposable resourceObject = null;

            // declaring these makes it clear we are testing the correct overload
            Func<Task<IDisposable>> resource = () =>
                {
                    resourceObject = new Disposable();
                    return CompletedTask.Canceled<IDisposable>();
                };

            CancellationTokenSource cts = new CancellationTokenSource();
            Func<Task<IDisposable>, Task> body = task =>
                Task.Factory.StartNew(
                    () =>
                    {
                        executed = true;
                        cts.Cancel();
                        cts.Token.ThrowIfCancellationRequested();
                    }, cts.Token);

            Task combinedTask = null;

            try
            {
                combinedTask = TaskBlocks.Using(resource, body);
                combinedTask.Wait();
                Assert.Fail("Expected a TaskCanceledException wrapped in an AggregateException");
            }
            catch (AggregateException ex)
            {
                Assert.IsNotNull(combinedTask, "Failed to create the combined task.");
                Assert.AreEqual(TaskStatus.Canceled, combinedTask.Status);
                Assert.AreEqual(1, ex.InnerExceptions.Count);
                Assert.IsInstanceOfType(ex.InnerExceptions[0], typeof(TaskCanceledException));
                Assert.IsNotNull(resourceObject);
                Assert.IsFalse(resourceObject.Disposed);
                Assert.IsFalse(executed);
            }
        }
		public void Using ()
		{
			var disposable = new Disposable ();

			var d = Expression.Parameter (typeof (Disposable), "d");

			var disposer = Expression.Lambda<Action<Disposable>> (
				CustomExpression.Using (
					d,
					Expression.Block (
						Expression.Call (d, typeof (Disposable).GetMethod ("Touch")))),
				d).Compile ();

			Assert.IsFalse (disposable.Touched);
			Assert.IsFalse (disposable.Disposed);

			disposer (disposable);

			Assert.IsTrue (disposable.Touched);
			Assert.IsTrue (disposable.Disposed);
		}
Пример #20
0
        public static Image ReadPortablePdb(Disposable<Stream> stream, string file_name)
        {
            try {
                var reader = new ImageReader (stream, file_name);
                var length = (uint) stream.value.Length;

                reader.image.Sections = new[] {
                    new Section {
                        PointerToRawData = 0,
                        SizeOfRawData = length,
                        VirtualAddress = 0,
                        VirtualSize = length,
                    }
                };

                reader.metadata = new DataDirectory (0, length);
                reader.ReadMetadata ();
                return reader.image;
            } catch (EndOfStreamException e) {
                throw new BadImageFormatException (stream.value.GetFileName (), e);
            }
        }
Пример #21
0
 ISymbolReader GetSymbolReader(ModuleDefinition module, Disposable<Stream> symbolStream, string fileName)
 {
     return new PortablePdbReader (ImageReader.ReadPortablePdb (symbolStream, fileName), module);
 }
Пример #22
0
 /// <summary>
 /// イベントを購読する。
 /// </summary>
 public static IDisposable Subscribe <T>(this IAsyncEvent <T> e, AsyncHandler <T> handler)
 {
     e.Add(handler);
     return(Disposable.Create(() => e.Remove(handler)));
 }
Пример #23
0
 public Disposable Create()
 {
     var d = new Disposable();
     this.Children.Add(d);
     return d;
 }
Пример #24
0
 internal PdbReader(Disposable<Stream> file)
 {
     this.pdb_file = file;
 }
Пример #25
0
 public static ImageWriter CreateWriter(ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
 {
     var writer = new ImageWriter (module, module.runtime_version, metadata, stream);
     writer.BuildSections ();
     return writer;
 }
		public void UsingException ()
		{
			var disposable = new Disposable ();

			var d = Expression.Parameter (typeof (Disposable), "d");

			var disposer = Expression.Lambda<Action<Disposable>> (
				CustomExpression.Using (
					d,
					Expression.Block (
						Expression.Throw (Expression.New (typeof (TestUsingException))),
						Expression.Call (d, typeof (Disposable).GetMethod ("Touch")))),
				d).Compile ();

			Assert.IsFalse (disposable.Touched);
			Assert.IsFalse (disposable.Disposed);

			try {
				disposer (disposable);
				Assert.Fail ();
			} catch (TestUsingException) {}

			Assert.IsFalse (disposable.Touched);
			Assert.IsTrue (disposable.Disposed);
		}
        public void InstanceRegisteredWith_InstancePerBackgroundJob_IsDisposedOnScopeDisposal()
        {
            var disposable = new Disposable();
            _container.Register<Disposable>((f) => disposable, new PerScopeLifetime());
            var activator = CreateActivator();

            using (var scope = activator.BeginScope())
            {
                var instance = scope.Resolve(typeof(Disposable));
            }

            Assert.IsTrue(disposable.Disposed);
        }
        public void TestUsing1_CompletedResource_CompletedBody_Disposable()
        {
            bool executed = false;
            Disposable resourceObject = null;

            // declaring these makes it clear we are testing the correct overload
            Func<Task<IDisposable>> resource = () =>
                {
                    resourceObject = new Disposable();
                    return CompletedTask.FromResult<IDisposable>(resourceObject);
                };
            Func<Task<IDisposable>, Task> body = task => Task.Factory.StartNew(() => executed = true);

            Task combinedTask = TaskBlocks.Using(resource, body);
            combinedTask.Wait();
            Assert.AreEqual(TaskStatus.RanToCompletion, combinedTask.Status);
            Assert.IsNotNull(resourceObject);
            Assert.IsTrue(resourceObject.Disposed);
            Assert.IsTrue(executed);
        }
        public void TestUsing1_CompletedResource_NullBody_Disposable()
        {
            bool executed = false;
            Disposable resourceObject = null;

            // declaring these makes it clear we are testing the correct overload
            Func<Task<IDisposable>> resource = () =>
                {
                    resourceObject = new Disposable();
                    return CompletedTask.FromResult<IDisposable>(resourceObject);
                };

            Func<Task<IDisposable>, Task> body = task =>
                {
                    executed = true;
                    return null;
                };

            Task combinedTask = null;

            try
            {
                combinedTask = TaskBlocks.Using(resource, body);
                combinedTask.Wait();
                Assert.Fail("Expected an TaskCanceledException wrapped in an AggregateException");
            }
            catch (AggregateException ex)
            {
                Assert.IsNotNull(combinedTask, "Failed to create the combined task.");
                Assert.AreEqual(TaskStatus.Canceled, combinedTask.Status);
                Assert.AreEqual(1, ex.InnerExceptions.Count);
                Assert.IsInstanceOfType(ex.InnerExceptions[0], typeof(TaskCanceledException));
                Assert.IsNotNull(resourceObject);
                Assert.IsTrue(resourceObject.Disposed);
                Assert.IsTrue(executed);
            }
        }
Пример #30
0
        ISymbolWriter GetSymbolWriter(ModuleDefinition module, Disposable<Stream> stream)
        {
            var metadata = new MetadataBuilder (module, this);
            var writer = ImageWriter.CreateDebugWriter (module, metadata, stream);

            return new PortablePdbWriter (metadata, module, writer);
        }
        public void TestUsing1_CompletedResource_FaultedBody_Disposable()
        {
            bool executed = false;
            Disposable resourceObject = null;

            // declaring these makes it clear we are testing the correct overload
            Func<Task<IDisposable>> resource = () =>
                {
                    resourceObject = new Disposable();
                    return CompletedTask.FromResult<IDisposable>(resourceObject);
                };

            Exception bodyException = new InvalidOperationException();
            Func<Task<IDisposable>, Task> body = task =>
                Task.Factory.StartNew(() =>
                {
                    executed = true;
                    throw bodyException;
                });

            Task combinedTask = null;

            try
            {
                combinedTask = TaskBlocks.Using(resource, body);
                combinedTask.Wait();
                Assert.Fail("Expected an InvalidOperationException wrapped in an AggregateException");
            }
            catch (AggregateException ex)
            {
                Assert.IsNotNull(combinedTask, "Failed to create the combined task.");
                Assert.AreEqual(TaskStatus.Faulted, combinedTask.Status);
                Assert.AreEqual(1, ex.InnerExceptions.Count);
                Assert.AreSame(bodyException, ex.InnerExceptions[0]);
                Assert.IsNotNull(resourceObject);
                Assert.IsTrue(resourceObject.Disposed);
                Assert.IsTrue(executed);
            }
        }