working on it ...

Filters

Explore Public Snippets

Sort by

Found 212 snippets matching: unittest

    public by maholtz  3391  1  6  1

    Windows Batch Script zum ausführen von PHPUnit

    Script zum erzeugen von PHPUnit. Die phpunit.phar muss im gleichen Verzeichnis liegen. Man kann festlegen ob nur eine bestimmte Datei oder ggf. ein Filter für bestimmte Testmethoden ausgeführt wird. Am Ende kann man den gleichen Test mit den selben Parametern erneut durchführen.
    @echo off
    REM Diese Datei führt die Unittests im lokalen Verzeichnis durch.
    REM
    REM Der Befehl "%~dp0" wechselt in den Ordner des Batch-Skripts. (sinnvoll bei Windows-Doppelklicks)
    
    rem # %~dp0 -> DirectoryPath ~dp0..
    @echo Unittest starten....
    
    SET testfile=%~dp0
    
    CHOICE /C NJ /M "Code Coverage Analyse durchfuehren (dauert laenger)?"
    IF ERRORLEVEL 2 (
       SET coverage= -v --testdox-html agile.html --testdox-text agile.txt --coverage-html coverage/
       GOTO start
    )
    
    SET /P testfile=Nur Bestimmte Datei testen? (Default = leer):
    IF NOT "%test%" == "" (
    	SET testfile=%testfile%
    )
    
    SET /p filter=Nur bestimmte Methoden testen? (Wildcard: *):
    IF NOT "%filter%" == "" (
       SET filter= --filter %filter%
    ) else (
       SET filter=
    )
    
    
    :start
    @echo phpunit-4.1.1.phar %filter% %coverage% --static-backup  --strict %testfile%
    php phpunit-4.1.1.phar %filter% %coverage% --static-backup  --strict %testfile%
    pause
    
    CHOICE /C NJ /M "Den selben Unittest noch einmal durchfuehren?"
    IF ERRORLEVEL 2 (
       goto start
    )
    
    :end
    @echo "Ende"
    
    CHOICE /C NJ /M "PHP Unit self-update durchfuehren?"
    IF ERRORLEVEL 2 (
       php phpunit-4.1.1.phar --self-update
       @echo Selbstupdate durchgefuehrt
       pause
    )
    

    public by cicero81  74  0  3  0

    Create your own test suite to run

    This set of methods allow to run a test suite without unit test frameworks like XUnit etc. It can be used across all the C# applications, e.g. UWP
        public static async Task<List<TestResult>> RunTests()
    		{
    			List<TestResult> res = new List<TestResult>();
    
    			// Consider the namespace of the tests:
    			IEnumerable<Type> typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "LiquidTextUWP.Tests");
    			foreach (Type testClass in typelist)
    			{
    				// Get all the test methods in the class:
    				foreach (MethodInfo method in testClass.GetMethods())
    				{
    					LTTestAttribute testAttr = method.GetCustomAttributes<LTTestAttribute>().FirstOrDefault();
    					if (testAttr == null)
    						continue;
    					object instance = Activator.CreateInstance(testClass);
    					try
    					{
    						if (testAttr.IsAsync)
    							await (Task) method.Invoke(instance, null);
    						else
    							method.Invoke(instance, null);
    						res.Add(new TestResult(true));
    					}
    					catch (Exception e)
    					{
    						res.Add(new TestResult(false, string.Format("{0} - {1}", e.Message, e.InnerException?.Message)));
    					}
    				}
    			}
    
    			return res;
    		}
    
    		private static IEnumerable<Type> GetTypesInNamespace(Assembly assembly, string nameSpace)
    		{
    			return assembly.GetTypes().Where(t => (t.Namespace != null) && t.Namespace.StartsWith(nameSpace));
    		}
    		
    		public struct TestResult
    	{
    		public bool Success { get; set; }
    		public string ErrorMsg { get; set; }
    
    		public TestResult(bool success, string msg = "")
    		{
    			Success = success;
    			ErrorMsg = msg;
    		}
    	}
    
    	[AttributeUsage(AttributeTargets.Method)]
    	public class LTTestAttribute : Attribute
    	{
    		public bool IsAsync { get; set; } = false;
    	}

    public by TristinDavis  1191  0  4  0

    Class to do Unit Test with TypeScript and TSTestAdapter

    Class to do Unit Test with TypeScript and TSTestAdapter: UnitTest.ts
    class Assert
    {
        public static AreEqual<T>(expected: T, actual: T, message: string = ""): void
        {
            if (expected !== actual)
            {
                throw "Assert.AreEqual failed. "
                    + "Expected: <" + expected + ">. "
                    + "Actual: <" + actual + ">. "
                    + message;
            }
        }
    
        public static AreNotEqual<T>(notExpected: T, actual: T, message: string = ""): void
        {
            if (notExpected === actual)
            {
                throw "Assert.AreNotEqual failed. "
                    + "Expected any value except: <" + notExpected + ">. "
                    + "Actual: <" + actual + ">. "
                    + message;
            }
        }
    
        public static AreNotSame<T>(notExpected: T, actual: T, message: string = ""): void
        {
            if (typeof (notExpected) !== "object"
                || typeof (actual) !== "object")
            {
                throw "Assert.AreSame failed. Do not pass value types to AreSame(). Consider using AreEqual()."
            }
    
            if (notExpected === actual)
            {
                throw "Assert.AreNotSame failed. " + message;
            }
        }
    
        public static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x, y) => boolean, message: string = ""): void
        {
            if (expected === null || actual === null)
            {
                throw "Assert.AreSequenceEqual failed. Do not pass null values to arrays. " + message;
            }
    
            if (expected === actual)
            {
                return;
            }
    
            if (expected.length !== actual.length)
            {
                throw "Assert.AreSequenceEqual failed. Length mismatch. "
                    + "Expected: <" + expected.length + ">. "
                    + "Actual: <" + actual.length + ">. "
                    + message;
            }
    
            if (!equals)
                equals = (x, y) => x == y;
    
            for (var i = 0, n = expected.length; i < n; i++)
            {
                if (!equals(expected[i], actual[i]))
                {
                    throw "Assert.AreSequenceEqual failed. "
                        + "Expected: <" + expected[i] + ">. Actual: <" + actual[i] + ">."
                        + message;
                }
            }
        }
    
        public static Fail(message: string = ""): void
        {
            throw "Assert.Fail failed. " + message;
        }
    
        // TODO: Implementation
        public static Inconclusive(message: string = ""): void
        {
            throw "NotImplementedException";
        }
    
        public static IsFalse(actual: boolean, message: string = ""): void
        {
            if (actual !== false)
            {
                throw "Assert.IsFalse failed. " + message;
            }
        }
    
        public static IsInstanceOfType(actual: any, expectedType: Function, message: string = ""): void
        {
            if (!(actual instanceof expectedType))
            {
                var expectedTypeName = /^function\s*([^(]*)/i.exec(expectedType + "")[1].toLocaleLowerCase();
                var actualTypeName = /^function\s*([^(]*)/i.exec(actual.constructor + "")[1].toLocaleLowerCase();
    
                throw "Assert.IsInstanceOfType failed. "
                    + "Expected type: <" + expectedTypeName + ">. "
                    + "Actual type: <" + actualTypeName + ">. "
                    + message;
            }
        }
    
        public static IsNotInstanceOfType(actual: any, wrongType: Function, message: string = ""): void
        {
            if (actual instanceof wrongType)
            {
                var wrongTypeName = /^function\s*([^(]*)/i.exec(wrongType + "")[1].toLocaleLowerCase();
                var actualTypeName = /^function\s*([^(]*)/i.exec(actual.constructor + "")[1].toLocaleLowerCase();
                
                throw "Assert.IsNotInstanceOfType failed. "
                    + "Expected any type except: <" + wrongTypeName + ">. "
                    + "Actual type: <" + actualTypeName + ">. "
                    + message;
            }
        }
    
        public static IsNotNull(actual: boolean, message: string = ""): void
        {
            if (actual === null)
            {
                throw "Assert.IsNotNull failed. " + message;
            }
        }
    
        public static IsNull(actual: boolean, message: string = ""): void
        {
            if (actual !== null)
            {
                throw "Assert.IsNull failed. " + message;
            }
        }
    
        public static IsTrue(actual: boolean, message: string = ""): void
        {
            if (actual !== true)
            {
                throw "Assert.IsTrue failed. " + message;
            }
        }
    
        public static Throws(fn: () => void, message: string = ""): void
        {
            var result = false;
    
            try
            {
                fn();
            }
            catch (ex)
            {
                result = true;
            }
    
            if (!result)
                throw "Assert.Throws failed. " + message;
        }
    }
    
    

    public by davis  1052  0  4  0

    Class to do Unit Test with TypeScript and TSTestAdapter

    Class to do Unit Test with TypeScript and TSTestAdapter: UnitTest.ts
    class Assert
    {
        public static AreEqual<T>(expected: T, actual: T, message: string = ""): void
        {
            if (expected !== actual)
            {
                throw "Assert.AreEqual failed. "
                    + "Expected: <" + expected + ">. "
                    + "Actual: <" + actual + ">. "
                    + message;
            }
        }
    
        public static AreNotEqual<T>(notExpected: T, actual: T, message: string = ""): void
        {
            if (notExpected === actual)
            {
                throw "Assert.AreNotEqual failed. "
                    + "Expected any value except: <" + notExpected + ">. "
                    + "Actual: <" + actual + ">. "
                    + message;
            }
        }
    
        public static AreNotSame<T>(notExpected: T, actual: T, message: string = ""): void
        {
            if (typeof (notExpected) !== "object"
                || typeof (actual) !== "object")
            {
                throw "Assert.AreSame failed. Do not pass value types to AreSame(). Consider using AreEqual()."
            }
    
            if (notExpected === actual)
            {
                throw "Assert.AreNotSame failed. " + message;
            }
        }
    
        public static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x, y) => boolean, message: string = ""): void
        {
            if (expected === null || actual === null)
            {
                throw "Assert.AreSequenceEqual failed. Do not pass null values to arrays. " + message;
            }
    
            if (expected === actual)
            {
                return;
            }
    
            if (expected.length !== actual.length)
            {
                throw "Assert.AreSequenceEqual failed. Length mismatch. "
                    + "Expected: <" + expected.length + ">. "
                    + "Actual: <" + actual.length + ">. "
                    + message;
            }
    
            if (!equals)
                equals = (x, y) => x == y;
    
            for (var i = 0, n = expected.length; i < n; i++)
            {
                if (!equals(expected[i], actual[i]))
                {
                    throw "Assert.AreSequenceEqual failed. "
                        + "Expected: <" + expected[i] + ">. Actual: <" + actual[i] + ">."
                        + message;
                }
            }
        }
    
        public static Fail(message: string = ""): void
        {
            throw "Assert.Fail failed. " + message;
        }
    
        // TODO: Implementation
        public static Inconclusive(message: string = ""): void
        {
            throw "NotImplementedException";
        }
    
        public static IsFalse(actual: boolean, message: string = ""): void
        {
            if (actual !== false)
            {
                throw "Assert.IsFalse failed. " + message;
            }
        }
    
        public static IsInstanceOfType(actual: any, expectedType: Function, message: string = ""): void
        {
            if (!(actual instanceof expectedType))
            {
                var expectedTypeName = /^function\s*([^(]*)/i.exec(expectedType + "")[1].toLocaleLowerCase();
                var actualTypeName = /^function\s*([^(]*)/i.exec(actual.constructor + "")[1].toLocaleLowerCase();
    
                throw "Assert.IsInstanceOfType failed. "
                    + "Expected type: <" + expectedTypeName + ">. "
                    + "Actual type: <" + actualTypeName + ">. "
                    + message;
            }
        }
    
        public static IsNotInstanceOfType(actual: any, wrongType: Function, message: string = ""): void
        {
            if (actual instanceof wrongType)
            {
                var wrongTypeName = /^function\s*([^(]*)/i.exec(wrongType + "")[1].toLocaleLowerCase();
                var actualTypeName = /^function\s*([^(]*)/i.exec(actual.constructor + "")[1].toLocaleLowerCase();
                
                throw "Assert.IsNotInstanceOfType failed. "
                    + "Expected any type except: <" + wrongTypeName + ">. "
                    + "Actual type: <" + actualTypeName + ">. "
                    + message;
            }
        }
    
        public static IsNotNull(actual: boolean, message: string = ""): void
        {
            if (actual === null)
            {
                throw "Assert.IsNotNull failed. " + message;
            }
        }
    
        public static IsNull(actual: boolean, message: string = ""): void
        {
            if (actual !== null)
            {
                throw "Assert.IsNull failed. " + message;
            }
        }
    
        public static IsTrue(actual: boolean, message: string = ""): void
        {
            if (actual !== true)
            {
                throw "Assert.IsTrue failed. " + message;
            }
        }
    
        public static Throws(fn: () => void, message: string = ""): void
        {
            var result = false;
    
            try
            {
                fn();
            }
            catch (ex)
            {
                result = true;
            }
    
            if (!result)
                throw "Assert.Throws failed. " + message;
        }
    }
    
    

    external by tito  228  1  3  0

    Example of mock-MotionEvent for unittest

    Example of mock-MotionEvent for unittest: utmotionevent.py
    # subclass for touch event in unit test
    class UTMotionEvent(MotionEvent):
    
        def depack(self, args):
            self.is_touch = True
            self.sx = args['x']
            self.sy = args['y']
            self.profile = ['pos']
            super(UTMotionEvent, self).depack(args)
            
    # then create a touch
    touch = UTMotionEvent("unittest", 1, {"x": 0, "y": 0})
    
    # dispatch it manually into kivy
    # using post_dispatch_input doesn't pass the touch to any input post-proc
    # we don't have the capability to dispatch manually a touch at the beginning
    # of the input pipeline, except if you create a touch provider and emit them.
    from kivy.base import EventLoop
    EventLoop.post_dispatch_input("begin", touch)
    
    # reminder, sx/sy must be size agnostic. So must be between 0-1 range.
    touch.move({"x": 0.1, "y": 0})
    EventLoop.post_dispatch_input("update", touch)
    
    EventLoop.post_dispatch_input("end", touch)
    
    
    
    

    external by hellwolf  228  0  3  0

    configure PyDev unittest file pattern

    configure PyDev unittest file pattern: gistfile1.txt
    Run configuration ->
    Python unittest ->
    (one of the configuration) ->
    Arguments ->
    PyUnit: Override PyUnit preferences for this launch?
      --include_files 'integration_*.py'
    
    

    external by Averroes  68  0  1  0

    unittest almostequal

    unittest almostequal: unittest_almostequal.py
    #!/usr/bin/env python
    #
    # Copyright 2007 Doug Hellmann.
    #
    #
    #                         All Rights Reserved
    #
    # Permission to use, copy, modify, and distribute this software and
    # its documentation for any purpose and without fee is hereby
    # granted, provided that the above copyright notice appear in all
    # copies and that both that copyright notice and this permission
    # notice appear in supporting documentation, and that the name of Doug
    # Hellmann not be used in advertising or publicity pertaining to
    # distribution of the software without specific, written prior
    # permission.
    #
    # DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
    # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
    # NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
    # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
    # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
    # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
    # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    #
    
    """Test for near equality
    
    """
    #end_pymotw_header
    
    import unittest
    
    class AlmostEqualTest(unittest.TestCase):
    
        def testEqual(self):
            self.failUnlessEqual(1.1, 3.3-2.2)
    
        def testAlmostEqual(self):
            self.failUnlessAlmostEqual(1.1, 3.3-2.2, places=1)
    
        def testNotAlmostEqual(self):
            self.failIfAlmostEqual(1.1, 3.3-2.0, places=1)
    
    if __name__ == '__main__':
        unittest.main()
    
    
    

    external by CoenM  34  3  2  0

    Unittest NLog messages

    Unittest NLog messages: TestNLogMessages.cs
    using System.Linq;
    using NLog;
    using NLog.Targets;
    using NUnit.Framework; // Using NUnit but any other unit test framework will do
    
    namespace com.github.gist.coenm.Test
    {
        public class Xyz
        {
            private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    
            public Xyz()
            {
                Logger.Debug(() => "starting with..   aldsfkjdslfkja l    <substring> sdfkj;lkdsfja s;lkfj          ends with");
            }
        }
    
        public class XyzTest
        {
            private MemoryTarget logTarget;
    
            [SetUp]
            public void SetUp()
            {
                ReInitializeLogTarget(LogLevel.Debug);
            }
    
            [TearDown]
            public void TearDown()
            {
                DisposeLogTarget();
            }
    
            [Test]
            public void TestAbc()
            {
                //arrange
    
                //act
                var sut = new Xyz();
    
                //assert
                Assert.That(logTarget.Logs.Count, Is.EqualTo(1));
                Assert.That(logTarget.Logs.First(), Is.StringContaining("substring"));
                Assert.That(logTarget.Logs.First(), Is.StringStarting("starting with.."));
                Assert.That(logTarget.Logs.First(), Is.StringEnding("ends with"));
            }
    
            private void DisposeLogTarget()
            {
                if(logTarget != null)
                    logTarget.Dispose();
            }
    
            private void ReInitializeLogTarget(LogLevel logLevel)
            {
                DisposeLogTarget();
    
                logTarget = new MemoryTarget { Layout = "${message}" };
                NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(logTarget, logLevel);
            }
        }
    }
    
    
    

    external by haradreborn  22  0  1  0

    Selenium unittest example structure

    Selenium unittest example structure: unit_test.py
    import unittest
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.common.exceptions import NoSuchElementException
    import os
    
    chromedriver = "D:\\chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = chromedriver
    
    class CS(unittest.TestCase):
    
        def setUp(self):
            self.driver = webdriver.Chrome(chromedriver)
    
        def test_samsung_apps_loading(self):
            driver = self.driver
            driver.get("http://www.samsung.com/ru/home")
            self.assertIn("Samsung", driver.title)
    
        def tearDown(self):
            self.driver.close()
    
    if __name__ == "__main__":
        unittest.main()
    
    
    

    external by Averroes  22  0  1  0

    unittest failwithmessage

    unittest failwithmessage: unittest_failwithmessage.py
    #!/usr/bin/env python
    #
    # Copyright 2007 Doug Hellmann.
    #
    #
    #                         All Rights Reserved
    #
    # Permission to use, copy, modify, and distribute this software and
    # its documentation for any purpose and without fee is hereby
    # granted, provided that the above copyright notice appear in all
    # copies and that both that copyright notice and this permission
    # notice appear in supporting documentation, and that the name of Doug
    # Hellmann not be used in advertising or publicity pertaining to
    # distribution of the software without specific, written prior
    # permission.
    #
    # DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
    # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
    # NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
    # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
    # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
    # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
    # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    #
    
    """A test that fails with a custom message.
    
    """
    #end_pymotw_header
    
    import unittest
    
    class FailureMessageTest(unittest.TestCase):
    
        def testFail(self):
            self.failIf(True, 'failure message goes here')
    
    if __name__ == '__main__':
        unittest.main()
    
    
    
    • Public Snippets
    • Channels Snippets