Пример #1
0
 public TestContainerAttribute(TestMode mode, UInt32 milestoneCount, UInt32 iterationCount)
 {
     _mode = mode;
     _milestoneCount = milestoneCount;
     _iterationCount = iterationCount;
     Metrics = TestMetrics.All;
 }
Пример #2
0
        public BenchmarkSettings(TestMode testMode, RunMode runMode, int numberOfIterations, int runTimeMilliseconds,
            IEnumerable<GcBenchmarkSetting> gcBenchmarks,
            IEnumerable<MemoryBenchmarkSetting> memoryBenchmarks,
            IEnumerable<CounterBenchmarkSetting> counterBenchmarks, string description, string skip)
        {
            TestMode = testMode;
            RunMode = runMode;
            NumberOfIterations = numberOfIterations;
            RunTime = TimeSpan.FromMilliseconds(runTimeMilliseconds == 0 ? DefaultRuntimeMilliseconds : runTimeMilliseconds);
            Description = description;
            Skip = skip;

            // Strip out any duplicates here
            // TODO: is it better to move that responsibility outside of the BenchmarkSettings class?

            GcBenchmarks = new HashSet<GcBenchmarkSetting>(gcBenchmarks).ToList();
            MemoryBenchmarks = new HashSet<MemoryBenchmarkSetting>(memoryBenchmarks).ToList();
            CounterBenchmarks = new HashSet<CounterBenchmarkSetting>(counterBenchmarks).ToList();

            DistinctGcBenchmarks =
                GcBenchmarks.Distinct(GcBenchmarkSetting.GcBenchmarkDistinctComparer.Instance).ToList();

            DistinctCounterBenchmarks =
                CounterBenchmarks.Distinct(CounterBenchmarkSetting.CounterBenchmarkDistinctComparer.Instance).ToList();

            DistinctMemoryBenchmarks =
                MemoryBenchmarks.Distinct(MemoryBenchmarkSetting.MemoryBenchmarkDistinctComparer.Instance).ToList();
        }
Пример #3
0
 public TestRecord( TestMode testMode, ISystem system, int threadId, long timeInTicks )
 {
     this.TestMode = testMode;
     this.System = system;
     this.ThreadId = threadId;
     this.Time = timeInTicks;
 }
Пример #4
0
 public void AggressiveParallel(TestMode testMode)
 {
     int count = 2;
     int errorCount = 0;
     ManualResetEvent evt = new ManualResetEvent(false);
     using (var c1 = Create(testMode))
     using (var c2 = Create(testMode))
     {
         WaitCallback cb = obj =>
         {
             var conn = (IDatabase)obj;
             conn.Multiplexer.ErrorMessage += delegate { Interlocked.Increment(ref errorCount); };
             
             for (int i = 0; i < 1000; i++)
             {
                 conn.LockTakeAsync("abc", "def", TimeSpan.FromSeconds(5));
             }
             conn.Ping();
             if (Interlocked.Decrement(ref count) == 0) evt.Set();
         };
         int db = testMode == TestMode.Twemproxy ? 0 : 2;
         ThreadPool.QueueUserWorkItem(cb, c1.GetDatabase(db));
         ThreadPool.QueueUserWorkItem(cb, c2.GetDatabase(db));
         evt.WaitOne(8000);
     }
     Assert.AreEqual(0, Interlocked.CompareExchange(ref errorCount, 0, 0));
 }
		public EnvironmentConfiguration()
		{
			//if env var NEST_INTEGRATION_VERSION is set assume integration mode
			//used by the build script FAKE
			this.ElasticsearchVersion = Environment.GetEnvironmentVariable("NEST_INTEGRATION_VERSION");
			if (!string.IsNullOrEmpty(ElasticsearchVersion))
				Mode = TestMode.Integration;
		}
Пример #6
0
 public Tests(TestMode mode)
 {
     _mode = mode;
     var codeBase = Assembly.GetExecutingAssembly().Location;
     var uri = new UriBuilder(codeBase);
     var path = Uri.UnescapeDataString(uri.Path);
         path = System.IO.Path.GetDirectoryName(path);
     Directory.SetCurrentDirectory(path);
 }
Пример #7
0
 public BenchmarkSettings(TestMode testMode, RunMode runMode, int numberOfIterations, int runTime,
     IEnumerable<GcBenchmarkSetting> gcBenchmarks,
     IEnumerable<MemoryBenchmarkSetting> memoryBenchmarks,
     IEnumerable<CounterBenchmarkSetting> counterBenchmarks)
     : this(
         testMode, runMode, numberOfIterations, runTime, gcBenchmarks, memoryBenchmarks,
         counterBenchmarks, string.Empty, string.Empty)
 {
 }
Пример #8
0
 public static String ModeToString(TestMode mode)
 {
     switch (mode)
     {
         case TestMode.Combined: return COMBINED;
         case TestMode.JIT: return JIT;
         case TestMode.Regular: return REGULAR;
         default: return String.Empty;
     }
 }
Пример #9
0
        internal TestForm(TestClientSettings settings, TestMode mode)
        {
            if (mode == TestMode.ProtoChannel)
                _clientRunner = new ProtoChannelClientRunner(this, settings);
            #if _NET_4
            else
                _clientRunner = new WcfClientRunner(this, settings);
            #endif

            InitializeComponent();
        }
		public void KVDictTest(byte[] kvform, IDictionary<string, string> dict, TestMode mode) {
			if ((mode & TestMode.Decoder) == TestMode.Decoder) {
				var d = this.keyValueForm.GetDictionary(new MemoryStream(kvform));
				foreach (string key in dict.Keys) {
					Assert.AreEqual(d[key], dict[key], "Decoder fault: " + d[key] + " and " + dict[key] + " do not match.");
				}
			}
			if ((mode & TestMode.Encoder) == TestMode.Encoder) {
				var e = KeyValueFormEncoding.GetBytes(dict);
				Assert.IsTrue(MessagingUtilities.AreEquivalent(e, kvform), "Encoder did not produced expected result.");
			}
		}
Пример #11
0
    public void TransparentWindow()
    {
#if UNITY_EDITOR_WIN || ((UNITY_STANDALONE_WIN || UNITY_WSA) && !UNITY_EDITOR)
        webView.Navigate(url);
        webView.Alpha = 0.005f;
        webView.Show();
        webView.SetTexture(CreateTexture());
#else
        Debug.LogWarning("Texturing feature is only supported on Win32/WSA/Windows Editor.");
#endif
        testMode = TestMode.TransparentWindow;
    }
Пример #12
0
        public IEnumerator AddTrackMultiple(TestMode mode)
        {
            MockSignaling.Reset(mode == TestMode.PrivateMode);

            var dependencies = CreateDependencies();
            var target       = new RenderStreamingInternal(ref dependencies);

            bool isStarted = false;

            target.onStart += () => { isStarted = true; };
            yield return(new WaitUntil(() => isStarted));

            Assert.That(isStarted, Is.True);

            var connectionId = "12345";

            target.CreateConnection(connectionId);
            bool isCreatedConnection = false;

            target.onCreatedConnection += _ => { isCreatedConnection = true; };
            yield return(new WaitUntil(() => isCreatedConnection));

            Assert.That(isCreatedConnection, Is.True);

            var camObj             = new GameObject("Camera");
            var camera             = camObj.AddComponent <Camera>();
            VideoStreamTrack track = camera.CaptureStreamTrack(1280, 720, 0);
            var transceiver1       = target.AddTrack(connectionId, track);

            Assert.That(transceiver1.Direction, Is.EqualTo(RTCRtpTransceiverDirection.SendOnly));

            var camObj2             = new GameObject("Camera2");
            var camera2             = camObj2.AddComponent <Camera>();
            VideoStreamTrack track2 = camera2.CaptureStreamTrack(1280, 720, 0);
            var transceiver2        = target.AddTrack(connectionId, track2);

            Assert.That(transceiver2.Direction, Is.EqualTo(RTCRtpTransceiverDirection.SendOnly));

            target.DeleteConnection(connectionId);
            bool isDeletedConnection = false;

            target.onDeletedConnection += _ => { isDeletedConnection = true; };
            yield return(new WaitUntil(() => isDeletedConnection));

            Assert.That(isDeletedConnection, Is.True);

            target.Dispose();
            track.Dispose();
            track2.Dispose();
            UnityEngine.Object.Destroy(camObj);
            UnityEngine.Object.Destroy(camObj2);
        }
Пример #13
0
		public YamlConfiguration(string configurationFile)
		{
			if (!File.Exists(configurationFile)) return;

			var config = File.ReadAllLines(configurationFile)
				.Where(l=>!l.Trim().StartsWith("#"))
				.ToDictionary(ConfigName, ConfigValue);

			this.Mode = GetTestMode(config["mode"]);
			this.ElasticsearchVersion = config["elasticsearch_version"];
			this.ForceReseed = bool.Parse(config["force_reseed"]);
			this.DoNotSpawnIfAlreadyRunning = bool.Parse(config["do_not_spawn"]);
		}
Пример #14
0
        public async ValueTask CancelEvent(TestMode mode)
        {
            var listener     = new EventListener();
            var eventManager = CreatEventManager(
                mode,
                new CancelAtHighEventListener(),
                listener
                );

            await eventManager.CallAsync(new SetValueEvent(1));

            Assert.Equal(0, listener.Value);
        }
Пример #15
0
        public EnvironmentConfiguration()
        {
            //if env var NEST_INTEGRATION_VERSION is set assume integration mode
            //used by the build script FAKE
            var version = Environment.GetEnvironmentVariable("NEST_INTEGRATION_VERSION");

            if (!string.IsNullOrEmpty(version))
            {
                Mode = TestMode.Integration;
            }

            this.ElasticsearchVersion = new ElasticsearchVersion(string.IsNullOrWhiteSpace(version) ? "2.0.0" : version);
        }
Пример #16
0
		public YamlConfiguration(string configurationFile)
		{
			if (!File.Exists(configurationFile)) return;

			var config = File.ReadAllLines(configurationFile)
				.Where(l=>!l.Trim().StartsWith("#"))
				.ToDictionary(ConfigName, ConfigValue);

			this.Mode = GetTestMode(config["mode"]);
			this.ElasticsearchVersion = new ElasticsearchVersion(config["elasticsearch_version"]);
			this.ForceReseed = bool.Parse(config["force_reseed"]);
			this.TestAgainstAlreadyRunningElasticsearch = bool.Parse(config["test_against_already_running_elasticsearch"]);
		}
Пример #17
0
        public void TakeLockAndExtend(TestMode mode)
        {
            bool withTran = mode == TestMode.MultiExec;
            using (var conn = Create(mode))
            {
                RedisValue right = Guid.NewGuid().ToString(),
                    wrong = Guid.NewGuid().ToString();

                int DB = mode == TestMode.Twemproxy ? 0 : 7;
                RedisKey Key = "lock-key";

                var db = conn.GetDatabase(DB);

                db.KeyDelete(Key);

                var t1 = db.LockTakeAsync(Key, right, TimeSpan.FromSeconds(20));
                var t1b = db.LockTakeAsync(Key, wrong, TimeSpan.FromSeconds(10));
                var t2 = db.LockQueryAsync(Key);
                var t3 = withTran ? db.LockReleaseAsync(Key, wrong) : null;
                var t4 = db.LockQueryAsync(Key);
                var t5 = withTran ? db.LockExtendAsync(Key, wrong, TimeSpan.FromSeconds(60)) : null;
                var t6 = db.LockQueryAsync(Key);
                var t7 = db.KeyTimeToLiveAsync(Key);
                var t8 = db.LockExtendAsync(Key, right, TimeSpan.FromSeconds(60));
                var t9 = db.LockQueryAsync(Key);
                var t10 = db.KeyTimeToLiveAsync(Key);
                var t11 = db.LockReleaseAsync(Key, right);
                var t12 = db.LockQueryAsync(Key);
                var t13 = db.LockTakeAsync(Key, wrong, TimeSpan.FromSeconds(10));

                Assert.NotEqual(default(RedisValue), right);
                Assert.NotEqual(default(RedisValue), wrong);
                Assert.NotEqual(right, wrong);
                Assert.True(conn.Wait(t1), "1");
                Assert.False(conn.Wait(t1b), "1b");
                Assert.Equal(right, conn.Wait(t2));
                if (withTran) Assert.False(conn.Wait(t3), "3");
                Assert.Equal(right, conn.Wait(t4));
                if (withTran) Assert.False(conn.Wait(t5), "5");
                Assert.Equal(right, conn.Wait(t6));
                var ttl = conn.Wait(t7).Value.TotalSeconds;
                Assert.True(ttl > 0 && ttl <= 20, "7");
                Assert.True(conn.Wait(t8), "8");
                Assert.Equal(right, conn.Wait(t9));
                ttl = conn.Wait(t10).Value.TotalSeconds;
                Assert.True(ttl > 50 && ttl <= 60, "10");
                Assert.True(conn.Wait(t11), "11");
                Assert.Null((string)conn.Wait(t12));
                Assert.True(conn.Wait(t13), "13");
            }
        }
Пример #18
0
 private ConnectionMultiplexer Create(TestMode mode)
 {
     switch (mode)
     {
         case TestMode.MultiExec:
             return Create();
         case TestMode.NoMultiExec:
             return Create(disabledCommands: new[] { "multi", "exec" });
         case TestMode.Twemproxy:
             return Create(proxy: Proxy.Twemproxy);
         default:
             throw new NotSupportedException(mode.ToString());
     }
 }
        public void GetAllWithDeletedItem(TestMode mode)
        {
            var store       = MakeStore(mode);
            var deletedItem = new TestEntity(unusedKey, 1, true);

            store.Init(new DataBuilder().Add(TestEntity.Kind, item1, item2, deletedItem)
                       .Add(OtherTestEntity.Kind, other1).Build());
            var result = store.All(TestEntity.Kind);

            Assert.Equal(2, result.Count);
            Assert.Equal(item1, result[item1.Key]);
            Assert.Equal(item2, result[item2.Key]);
            Assert.False(result.ContainsKey(deletedItem.Key));
        }
        /// <summary>
        /// Retrieve the test list for given mode.
        /// </summary>
        /// <param name="testMode"></param>
        /// <param name="assemblyNames">Can be null.</param>
        /// <param name="callback"></param>
        void RetrieveTestList(TestMode testMode, string[] assemblyNames, Action <ITestAdaptor, ExecutionSettings> callback)
        {
            var filter = new Filter {
                testMode = testMode, assemblyNames = assemblyNames
            };
            var executionSettings = new ExecutionSettings {
                filter = filter, filters = new Filter[0]
            };

            api.RetrieveTestList(testMode, rootTest =>
            {
                callback(rootTest, executionSettings);
            });
        }
Пример #21
0
        public IEnumerator Construct(TestMode mode)
        {
            MockSignaling.Reset(mode == TestMode.PrivateMode);

            var dependencies = CreateDependencies();
            var target       = new RenderStreamingInternal(ref dependencies);

            bool isStarted = false;

            target.onStart += () => { isStarted = true; };
            yield return(new WaitUntil(() => isStarted));

            target.Dispose();
        }
Пример #22
0
        private static XmlReader CreateReader(TestMode mode, XmlBuffer xmlBuffer, string startAt)
        {
            switch (mode)
            {
            case TestMode.FullDocument:
                return(xmlBuffer.CreateReader());

            case TestMode.StartAtSpecifiedElement:
                return(xmlBuffer.CreateReaderAt(startAt));

            default:
                throw new InvalidOperationException("Reader cannot be created in mode " + mode);
            }
        }
        void OnRunFinished(ITestResultAdaptor testResults)
        {
            // Only process runs we started
            if (isRunning)
            {
                m_Current              = 0;
                m_TestCasePassedCount += testResults != null ? testResults.PassCount : 0;

                // We consider runs with skipped tests as passed (and null results means no test for this test mode, which we consider passed also)
                var passed = // There must be at least one test
                             testResults == null ||
                             (testResults.TestStatus == TestStatus.Passed || testResults.TestStatus == TestStatus.Skipped);

                // There must be at least one test total
                if (m_TestMode == 0 && m_TestCasePassedCount == 0)
                {
                    passed = false;
                }

                if (m_TestMode != 0 && passed)
                {
                    Run();
                }
                else
                {
                    //
                    // Test Run is completed
                    if (passed)
                    {
                        Debug.Log(s_TestCompleteMessage + Environment.NewLine + "    " + m_TestCaseCount + " tests were run.");
                    }
                    else
                    {
                        if (m_TestCasePassedCount == 0)
                        {
                            Debug.LogWarning(k_NoTestMessage);
                        }
                        else
                        {
                            Debug.LogWarning("Some tests have failed. Please review the test runner for details.");
                        }
                    }

                    onTestResultsUpdate(passed, packageName);
                    onTestResultsEnded();
                    Reset();
                }
            }
        }
Пример #24
0
        protected async Task TestAsync(string text, string expectedType, TestMode mode,
                                       SourceCodeKind sourceCodeKind = SourceCodeKind.Regular)
        {
            MarkupTestFile.GetSpan(text.NormalizeLineEndings(), out text, out var textSpan);

            var document = fixture.UpdateDocument(text, sourceCodeKind);

            await TestWorkerAsync(document, textSpan, expectedType, mode);

            if (await CanUseSpeculativeSemanticModelAsync(document, textSpan.Start))
            {
                var document2 = fixture.UpdateDocument(text, sourceCodeKind, cleanBeforeUpdate: false);
                await TestWorkerAsync(document2, textSpan, expectedType, mode);
            }
        }
Пример #25
0
        private void BatchRunConverter(string tool, string inputFilter, TestMode testMode)
        {
            var sb = new StringBuilder();

            string testDirectory = SarifConverterTests.TestDirectory + "\\" + tool;

            string[] testFiles = Directory.GetFiles(testDirectory, inputFilter);

            foreach (string file in testFiles)
            {
                RunConverter(sb, tool, file, testMode);
            }

            sb.Length.Should().Be(0, FormatFailureReason(sb, tool));
        }
Пример #26
0
        // Runs the test suite for a given test mode:
        static void RunAllTestsForMode(TestMode t)
        {
            switch (t)
            {
            case TestMode.BOWYER_WATSON:
                Console.WriteLine("Test Results for BOWYER/WATSON:\n");
                break;

            case TestMode.BRUTE_FORCE_SCALE_RES:
                Console.WriteLine("Test Results for BRUTE FORCE (scaling width/height):\n");
                break;

            case TestMode.BRUTE_FORCE_SCALE_PTS:
                Console.WriteLine("Test Results for BRUTE FORCE (scaling num points):\n");
                break;
            }

            Console.WriteLine("Trial:\t\tPoints:\t\tRange:\t\tTime:\t\t");

            if (t == TestMode.BRUTE_FORCE_SCALE_RES)
            {
                foreach (int r in ranges)
                {
                    long totalTime = 0;
                    for (int i = 0; i < numRuns; i++)
                    {
                        totalTime += RunTests(i, numPtsForRange, r, t);
                    }
                    long avg = totalTime / numRuns;
                    Console.WriteLine("Average completion time: " + avg + "\n");
                }
            }
            else
            {
                foreach (int numPt in numPts)
                {
                    long totalTime = 0;
                    for (int i = 0; i < numRuns; i++)
                    {
                        // The range of points is the current numbef or points
                        // times the range multipler. e.g. 10 points -> 50 range
                        totalTime += RunTests(i, numPt, numPt * rangeMultiplier, t);
                    }
                    long avg = totalTime / numRuns;
                    Console.WriteLine("Average completion time: " + avg + "\n");
                }
            }
        }
        public void OneInstanceCanDetectIfAnotherInstanceHasInitializedStore(TestMode mode)
        {
            if (!InstancesShareSameData)
            {
                return; // XUnit has no way to mark a test as "skipped"
            }

            ClearAllData();
            var store1 = MakeStore(mode);

            store1.Init(new DataBuilder().Add(TestEntity.Kind, item1).Build());

            var store2 = MakeStore(mode);

            Assert.True(store2.Initialized());
        }
Пример #28
0
        public YamlConfiguration(string configurationFile)
        {
            if (!File.Exists(configurationFile))
            {
                return;
            }

            var config = File.ReadAllLines(configurationFile)
                         .Where(l => !l.Trim().StartsWith("#"))
                         .ToDictionary(ConfigName, ConfigValue);

            this.Mode = GetTestMode(config["mode"]);
            this.ElasticsearchVersion       = config["elasticsearch_version"];
            this.ForceReseed                = bool.Parse(config["force_reseed"]);
            this.DoNotSpawnIfAlreadyRunning = bool.Parse(config["do_not_spawn"]);
        }
Пример #29
0
        public IEnumerator OpenConnectionThrowException(TestMode mode)
        {
            MockSignaling.Reset(mode == TestMode.PrivateMode);

            var dependencies = CreateDependencies();
            var target       = new RenderStreamingInternal(ref dependencies);

            bool isStarted = false;

            target.onStart += () => { isStarted = true; };
            yield return(new WaitUntil(() => isStarted));

            Assert.That(() => target.CreateConnection(null), Throws.TypeOf <ArgumentException>());
            Assert.That(() => target.CreateConnection(string.Empty), Throws.TypeOf <ArgumentException>());
            target.Dispose();
        }
        /// <summary>
        /// Registers device for receiving Push Notifications
        /// </summary>
        /// <param name="mode">Application mode</param>
        internal void EnablePushNotificationAsync(TestMode mode)
        {
            _mode = mode;
#if UNITY_ANDROID && !UNITY_EDITOR
            _notificationsService.GetToken(result =>
            {
                _token = result;
            });
#endif
#if UNITY_IOS && !UNITY_EDITOR
            NotificationServices.RegisterForNotifications(
                NotificationType.Alert
                | NotificationType.Badge
                | NotificationType.Sound);
#endif
        }
Пример #31
0
        public Test(Gothic gothic, TestMode testMode) : base(gothic)
        {
            Mode = testMode;

            compilingAssetsWatcher.OnFileCompile = (compilingFile) =>
            {
                if (compilingFile.Contains("MENU.DAT"))
                {
                    if ((Mode == TestMode.Full &&
                         (assetsCompiled == false)))
                    {
                        gothic.EndProcess();
                    }
                }
            };
        }
        public YamlConfiguration(string configurationFile)
        {
            if (!File.Exists(configurationFile))
            {
                return;
            }

            var config = File.ReadAllLines(configurationFile)
                         .Where(l => !l.Trim().StartsWith("#"))
                         .ToDictionary(ConfigName, ConfigValue);

            this.Mode = GetTestMode(config["mode"]);
            this.ElasticsearchVersion = new ElasticsearchVersion(config["elasticsearch_version"]);
            this.ForceReseed          = bool.Parse(config["force_reseed"]);
            this.TestAgainstAlreadyRunningElasticsearch = bool.Parse(config["test_against_already_running_elasticsearch"]);
        }
Пример #33
0
        public Global()
        {
            ProTracReq       = new byte[0] {
            };
            CellScanReq      = new byte[0] {
            };
            UnSpeCellScanReq = new byte[0] {
            };
            DebugReq         = new byte[0] {
            };

            testStatus       = TestStatus.Stop;
            testMode         = TestMode.RealTime;
            scanMode         = ScanMode.Single;
            connectionStatus = false;
        }
Пример #34
0
 public void KVDictTest(byte[] kvform, IDictionary <string, string> dict, TestMode mode)
 {
     if ((mode & TestMode.Decoder) == TestMode.Decoder)
     {
         var d = this.keyValueForm.GetDictionary(new MemoryStream(kvform));
         foreach (string key in dict.Keys)
         {
             Assert.AreEqual(d[key], dict[key], "Decoder fault: " + d[key] + " and " + dict[key] + " do not match.");
         }
     }
     if ((mode & TestMode.Encoder) == TestMode.Encoder)
     {
         var e = KeyValueFormEncoding.GetBytes(dict);
         Assert.IsTrue(MessagingUtilities.AreEquivalent(e, kvform), "Encoder did not produced expected result.");
     }
 }
Пример #35
0
        public void Configure(TestMode testMode, Guid localInterfaceGuid, string address, bool ipv6, UInt16 port)
        {
            this.ipv6Mode = ipv6;
            localPort     = port;

            if (testMode == TestMode.Wlan)
            {
                localAddress = NetworkInterfaceDataPathTests.GetWirelessEndpoint(ipv6Mode);
            }
            else
            {
                localAddress = NetworkInterfaceDataPathTests.GetLanEndpoint(ipv6Mode, localInterfaceGuid);
            }

            this.identifier = String.Format(CultureInfo.InvariantCulture, "{0}:{1}", localAddress, localPort);
            testLogger.LogComment("MulticastReceiver[{0}]  local address", this.identifier);


            testLogger.LogTrace("Creating Multicast Receive Socket");
            if (ipv6Mode)
            {
                if (testMode == TestMode.Wlan)
                {
                    using (Wlan wlanApi = new Wlan())
                    {
                        var wlanInterfaceList = wlanApi.EnumWlanInterfaces();
                        if (wlanInterfaceList.Count < 1)
                        {
                            throw new TestConfigException("No WLAN Interfaces were discovered.  Ensure that WLAN interfaces are enabled, discoverable, and operational.");
                        }
                        var wlanInterface = wlanInterfaceList[0];

                        UInt32 wlanInterfaceIndex = NetworkInterfaceDataPathTests.GetNetworkIndex(wlanInterface.Id);
                        listenSocket = sockets.CreateMulticastSocket(localAddress, localPort, address, port, wlanInterfaceIndex);
                    }
                }
                else
                {
                    UInt32 lanInterfaceIndex = NetworkInterfaceDataPathTests.GetNetworkIndex(localInterfaceGuid);
                    listenSocket = sockets.CreateMulticastSocket(localAddress, localPort, address, port, lanInterfaceIndex);
                }
            }
            else
            {
                listenSocket = sockets.CreateMulticastSocket(localAddress, localPort, address, port);
            }
        }
Пример #36
0
        private void CollectTestMethods(Assembly assembly, ITestResultEndPoint results, out IList <TestMethodInfo> sequentialTestMethods, out IList <TestMethodInfo> parallelTestMethods)
        {
            _log.Debug(nameof(CollectTestMethods));

            sequentialTestMethods = new List <TestMethodInfo>();
            parallelTestMethods   = new List <TestMethodInfo>();

            foreach (Type type in assembly.GetTypes())
            {
                _log.Debug($"Searching type {type.Format()}.");

                TestClassAttribute c_attr           = type.GetCustomAttribute <TestClassAttribute>();
                TestMode           classLevelMode   = c_attr != null ? c_attr.TestMode : TestMode.Parallel;
                Boolean            classLevelIgnore = c_attr != null && c_attr.IsIgnored;

                foreach (MethodInfo testMethod in type.GetRuntimeMethods().Where(m => m.GetCustomAttributes <TestMethodAttribute>().Count() > 0))
                {
                    _log.Info($"Found test method {type.Format()}.{testMethod.Name.Format()}.");
                    TestMethodAttribute m_attr = testMethod.GetCustomAttribute <TestMethodAttribute>();

                    if (classLevelIgnore)
                    {
                        _log.Debug($"Class ignored: {c_attr.IgnoreReason.Format()}");
                        results.IgnoreTestMethod(testMethod, $"Class ignored: {c_attr.IgnoreReason.Format()}");
                    }
                    else if (m_attr.IsIgnored)
                    {
                        _log.Debug($"Method ignored: {m_attr.IgnoreReason.Format()}");
                        results.IgnoreTestMethod(testMethod, $"Method ignored: {m_attr.IgnoreReason.Format()}");
                    }
                    else
                    {
                        if (classLevelMode == TestMode.Sequential || m_attr.TestMode == TestMode.Sequential || Configuration.TestMethodModeOverride == TestModeOverrides.Sequential)
                        {
                            _log.Info($"Adding sequential test method {type.Format()}.{testMethod.Name.Format()}.");
                            sequentialTestMethods.Add(new TestMethodInfo(results, testMethod));
                        }
                        else
                        {
                            _log.Info($"Adding parallel test method {type.Format()}.{testMethod.Name.Format()}.");
                            parallelTestMethods.Add(new TestMethodInfo(results, testMethod));
                        }
                    }
                }
            }
        }
Пример #37
0
        public void TestBasicLockTaken(TestMode testMode)
        {
            using (var conn = Create(testMode))
            {
                var db = conn.GetDatabase(0);
                db.KeyDelete("lock-exists");
                db.StringSet("lock-exists", "old-value", TimeSpan.FromSeconds(20));
                var taken    = db.LockTakeAsync("lock-exists", "new-value", TimeSpan.FromSeconds(10));
                var newValue = db.StringGetAsync("lock-exists");
                var ttl      = db.KeyTimeToLiveAsync("lock-exists");

                Assert.IsFalse(conn.Wait(taken), "taken");
                Assert.AreEqual("old-value", (string)conn.Wait(newValue));
                var ttlValue = conn.Wait(ttl).Value.TotalSeconds;
                Assert.IsTrue(ttlValue >= 18 && ttlValue <= 20, "ttl");
            }
        }
Пример #38
0
        /// <summary>
        /// Send a Test command, this moved the ears and rotate colors
        /// </summary>
        /// <param name="testType">Ears or Leds</param>
        /// <param name="needRequestId">true if you want a confirmation, by default, yes</param>
        /// <param name="cancelAfterSeconds">Cancel waiting for the answer after the seconds defined. By default, it will wait indefinitely</param>
        /// <returns>Response object</returns>
        public Response Test(TestType testType, bool needRequestId = true, int cancelAfterSeconds = -1)
        {
            TestMode test = new TestMode()
            {
                Test = testType
            };
            Guid reqId;

            if (needRequestId)
            {
                reqId = Guid.NewGuid();
                _LastRequestId.Add(reqId.ToString(), null);
                test.RequestId = reqId.ToString();
            }

            return(SendMessageProcessResponse(JsonConvert.SerializeObject(test), reqId, cancelAfterSeconds));
        }
Пример #39
0
        public async Task CancelPriority(TestMode mode)
        {
            var listener     = new PriorityEventListener();
            var eventManager = CreatEventManager(
                mode,
                new CancelAtHighEventListener(),
                listener
                );

            await eventManager.CallAsync(new SetValueEvent(1));

            Assert.Equal(new[]
            {
                EventPriority.Monitor,
                EventPriority.Highest,
            }, listener.Priorities);
        }
Пример #40
0
        public void Configure(TestMode testMode, Guid localInterfaceGuid, string address, bool ipv6, UInt16 port)
        {
            this.ipv6Mode = ipv6;
            localPort     = port;

            if (testMode == TestMode.Wlan)
            {
                localAddress = NetworkInterfaceDataPathTests.GetWirelessEndpoint(ipv6Mode);
            }
            else
            {
                localAddress = NetworkInterfaceDataPathTests.GetLanEndpoint(ipv6Mode, localInterfaceGuid);
            }
            this.identifier = String.Format(CultureInfo.InvariantCulture, "{0}:{1}", localAddress, localPort);
            testLogger.LogComment("BroadcastReceiver[{0}] local address", this.identifier);

            listenSocket = sockets.CreateUdpSocket(localAddress, localPort, ipv6Mode);
        }
Пример #41
0
        public void matches_on_test()
        {
            var theTest   = new Test("test1");
            var otherTest = new Test("test2");

            var subject = new ScreenLocator <Test>(theTest);

            var testView = MockRepository.GenerateMock <ITestView>();

            var modes = new TestMode[] { new PreviewMode(null, null, null) };
            var presenterThatDoesNotMatch = new TestScreen(null, null, otherTest, new TestStateManager(new TestConverter(), otherTest), null, null, null);
            var presenterThatShouldMatch  = new TestScreen(null, null, theTest, new TestStateManager(new TestConverter(), theTest), null, null, null);
            var differentTypeOfPresenter  = MockRepository.GenerateMock <IScreen>();

            subject.Matches(presenterThatDoesNotMatch).ShouldBeFalse();
            subject.Matches(presenterThatShouldMatch).ShouldBeTrue();
            subject.Matches(differentTypeOfPresenter).ShouldBeFalse();
        }
Пример #42
0
        public async Task TestBasicLockTaken(TestMode testMode)
        {
            using (var conn = Create(testMode))
            {
                var db  = conn.GetDatabase();
                var key = Me();
                db.KeyDelete(key, CommandFlags.FireAndForget);
                db.StringSet(key, "old-value", TimeSpan.FromSeconds(20), flags: CommandFlags.FireAndForget);
                var taken    = db.LockTakeAsync(key, "new-value", TimeSpan.FromSeconds(10));
                var newValue = db.StringGetAsync(key);
                var ttl      = db.KeyTimeToLiveAsync(key);

                Assert.False(await taken, "taken");
                Assert.Equal("old-value", await newValue);
                var ttlValue = (await ttl).Value.TotalSeconds;
                Assert.True(ttlValue >= 18 && ttlValue <= 20, "ttl");
            }
        }
Пример #43
0
        private void TestBandwidth(Context context, Device[] devices, int start, int end, int increment, TestMode testMode, MemoryCopyKind memoryCopyKind, PrintMode printMode, AccessMode accessMode, MemoryMode memoryMode, int startDevice, int endDevice)
        {
            switch (testMode)
            {
            case TestMode.Quick:
                TestBandwidthQuick(context, devices, DefaultSize, memoryCopyKind, printMode, accessMode, memoryMode, startDevice, endDevice);
                break;

            case TestMode.Range:
                TestBandwidthRange(context, devices, start, end, increment, memoryCopyKind, printMode, accessMode, memoryMode, startDevice, endDevice);
                break;

            case TestMode.Shmoo:
                TestBandwidthShmoo(context, devices, memoryCopyKind, printMode, accessMode, memoryMode, startDevice, endDevice);
                break;

            default:
                break;
            }
        }
Пример #44
0
        /// <summary>
        ///  见接口
        /// </summary>
        /// <param name="renderer"></param>
        /// <param name="screenTarget"></param>
        public void RenderFullScene(ISceneRenderer renderer, RenderTarget screenTarget, RenderMode mode)
        {
            Microsoft.Xna.Framework.Input.KeyboardState ks = Microsoft.Xna.Framework.Input.Keyboard.GetState();
            if (ks.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.C) &&
                lastState.IsKeyUp(Microsoft.Xna.Framework.Input.Keys.C))
            {
                testMode++;
                if (testMode > TestMode.Blurred)
                    testMode = TestMode.Final;
            }
            lastState = ks;

            if (testMode == TestMode.Original)
            {
                renderer.RenderScene(screenTarget, RenderMode.Final);
                return;
            }
            if (testMode == TestMode.Normal)
            {
                renderer.RenderScene(screenTarget, RenderMode.DeferredNormal);
                return;
            }

            renderer.RenderScene(nrmDepthBuffer, RenderMode.DeferredNormal);

            renderer.RenderScene(colorBuffer, RenderMode.Final);


            Viewport vp = renderSys.Viewport;

            ShaderSamplerState sampler1;
            sampler1.AddressU = TextureAddressMode.Clamp;
            sampler1.AddressV = TextureAddressMode.Clamp;
            sampler1.AddressW = TextureAddressMode.Clamp;
            sampler1.BorderColor = ColorValue.Transparent;
            sampler1.MagFilter = TextureFilter.Point;
            sampler1.MaxAnisotropy = 0;
            sampler1.MaxMipLevel = 0;
            sampler1.MinFilter = TextureFilter.Point;
            sampler1.MipFilter = TextureFilter.None;
            sampler1.MipMapLODBias = 0;


            ShaderSamplerState sampler2 = sampler1;
            sampler2.MagFilter = TextureFilter.Linear;
            sampler2.MinFilter = TextureFilter.Linear;

            #region 边缘合成
            renderSys.SetRenderTarget(0, testMode == TestMode.Edge ? screenTarget : edgeResultBuffer);
            edgeEff.Begin();

            edgeEff.SetSamplerStateDirect(0, ref sampler1);
            edgeEff.SetSamplerStateDirect(1, ref sampler1);

            edgeEff.SetTextureDirect(0, nrmDepthBuffer.GetColorBufferTexture());
            edgeEff.SetTextureDirect(1, testMode == TestMode.Edge ? whitePixel : colorBuffer.GetColorBufferTexture());

            Vector2 nrmBufSize = new Vector2(vp.Width, vp.Height);
            edgeEff.SetValue("normalBufferSize", ref nrmBufSize);
            DrawBigQuad();
            edgeEff.End();
            #endregion

            if (testMode == TestMode.Edge)
                return;
            if (testMode == TestMode.Depth)
            {
                renderSys.SetRenderTarget(0, screenTarget);
                depthViewEff.Begin();
                depthViewEff.SetSamplerStateDirect(0, ref sampler1);
                depthViewEff.SetTextureDirect(0, nrmDepthBuffer.GetColorBufferTexture());
                DrawBigQuad();
                depthViewEff.End();
                return;
            }
            #region 高斯X
            renderSys.SetRenderTarget(0, blurredRt1);

            gaussBlur.Begin();

            gaussBlur.SetSamplerStateDirect(0, ref sampler1);
            gaussBlur.SetTextureDirect(0, edgeResultBuffer.GetColorBufferTexture());

            for (int i = 0; i < SampleCount; i++)
            {
                gaussBlur.SetValueDirect(i, ref guassFilter.SampleOffsetsX[i]);
                gaussBlur.SetValueDirect(i + 15, guassFilter.SampleWeights[i]);
            }

            DrawSmallQuad();

            gaussBlur.End();
            #endregion

            #region 高斯Y

            renderSys.SetRenderTarget(0, testMode == TestMode.Blurred ? screenTarget : blurredRt2);
            gaussBlur.Begin();

            gaussBlur.SetSamplerStateDirect(0, ref sampler1);
            gaussBlur.SetTextureDirect(0, blurredRt1.GetColorBufferTexture());

            for (int i = 0; i < SampleCount; i++)
            {
                gaussBlur.SetValueDirect(i, ref guassFilter.SampleOffsetsY[i]);
                gaussBlur.SetValueDirect(i + 15, guassFilter.SampleWeights[i]);
            }
            if (testMode == TestMode.Blurred)
            {
                DrawBigQuad();
            }
            else
            {
                DrawSmallQuad();
            }

            gaussBlur.End();


            #endregion

            if (testMode == TestMode.Blurred)
                return;

            #region DOF合成

            renderSys.SetRenderTarget(0, screenTarget);

            compEff.Begin();

            compEff.SetSamplerStateDirect(0, ref sampler1);
            compEff.SetSamplerStateDirect(1, ref sampler2);
            compEff.SetSamplerStateDirect(2, ref sampler2);

            compEff.SetTextureDirect(0, edgeResultBuffer.GetColorBufferTexture());
            compEff.SetTextureDirect(1, blurredRt2.GetColorBufferTexture());
            compEff.SetTextureDirect(2, nrmDepthBuffer.GetColorBufferTexture());

            //if (camera != null)
            //{
            //    float focNear = (camera.Position.Length() - PlanetEarth.PlanetRadius) / camera.FarPlane;
            //    compEff.SetValue("FocusNear", focNear);
            //}
            //else 
            //{
            //    compEff.SetValue("FocusNear", 0.3f);
            //}

            renderSys.RenderStates.AlphaBlendEnable = true;
            renderSys.RenderStates.SourceBlend = Blend.SourceAlpha;
            renderSys.RenderStates.DestinationBlend = Blend.InverseSourceAlpha;
            renderSys.RenderStates.BlendOperation = BlendFunction.Add;

            DrawBigQuad();

            compEff.End();
            #endregion
        }
Пример #45
0
		/// <summary>
		/// Does classic generation of the roof
		/// </summary>
		/// <param name="mode">The mode for this generation</param>
		/// <param name="height">The height at which the tiling occurs</param>
		/// <param name="hue">The hue for the roof</param>
		/// <returns>True if generation is succesful</returns>
		public bool GenerateClassic( TestMode mode, int height, int hue )
		{
			int[] roofIDs = new int[ m_RoofImage.Width * m_RoofImage.Height ];
			bool fail = false;

			// Revert any sign changes due to image processing
			for ( int i = 0; i < m_RoofImage.Width * m_RoofImage.Height; i++ )
			{
				// Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert
				if ( m_RoofImage.Data[ i ] < 0 )
					m_RoofImage.Data[ i ] = - m_RoofImage.Data[ i ];
				// Issue 10 - End
			}

			// Calculate the roof ids
			for ( int i = 0; i < m_RoofImage.Width * m_RoofImage.Height; i++ )
			{
				// Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert
				if ( m_RoofImage.Data[ i ] == 0 )
				// Issue 10 - End
				{
					roofIDs[ i ] = 0;
				}
				else
				{
					uint flags = RoofingHelper.GetFlags( MakeLine( i - m_RoofImage.Width ), MakeLine( i ), MakeLine( i + m_RoofImage.Width ) );
					roofIDs[ i ] = m_TileSet.FindID( flags );

					if ( roofIDs[ i ] == 0 )
					{
						// Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert
						m_RoofImage.Data[ i ] = - m_RoofImage.Data[ i ];
						// Issue 10 - End
						fail = true;
					}

					if ( mode != TestMode.NoTest )
					{
						bool corner = !((flags & ~0x88878778) != 0) ||
							!((flags & ~0x88887877) != 0) ||
							!((flags & ~0x77878888) != 0) ||
							!((flags & ~0x87787888) != 0) ||
							!((flags & ~0x87777777) != 0) ||
							!((flags & ~0x77877777) != 0) ||
							!((flags & ~0x77777877) != 0) ||
							!((flags & ~0x77777778) != 0);

						if ( mode == TestMode.Test && !corner )
						{
							roofIDs[ i ] = 0;
						}

						if ( mode == TestMode.Rest && corner )
						{
							roofIDs[ i ] = 0;
						}
					}
				}
			}

			if ( fail )
			{
				m_RoofImage.CreateImage();

				// Request redraw image
				if ( RoofImageChanged != null )
				{
					RoofImageChanged( this, new EventArgs() );
				}

				if ( MessageBox.Show(
					Pandora.Localization.TextProvider[ "Roofing.MissTiles" ],
					"",
					MessageBoxButtons.YesNo,
					MessageBoxIcon.Question ) == DialogResult.No )
				{
					return false;
				}
			}

			string idFormat = hue > 0 ? "static {0} set hue " + hue.ToString() : "static {0}";

			int dx = 0;
			int dy = 0;
			int p = 0;

			int tilex = 0;
			int tiley = 0;
			int tilew = 0;
			int tileh = 0;

			int tilez = 0;
			int tileid = 0;

			for ( int y = 0; y < m_RoofImage.Height; y++ )
			{
				for ( int x = 0; x < m_RoofImage.Width; x++, p++ )
				{
					if ( roofIDs[ p ] == 0 )
					{
						continue;
					}

					for ( dx = 1; dx + x < m_RoofImage.Width; dx++ )
					{
						// Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert
						if ( ( roofIDs[ p + dx ] != roofIDs[ p ] ) || ( m_RoofImage.Data[ p ] != m_RoofImage.Data[ p + dx ] ) )
						// Issue 10 - End
						{
							break;
						}
					}

					for ( dy = 1; dy + y < m_RoofImage.Height; dy++ )
					{
						if ( ( (int) roofIDs[ p + m_RoofImage.Width * dy ] != roofIDs[ p ] ) ||
							// Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert
							( m_RoofImage.Data[ p ] != m_RoofImage.Data[ p + m_RoofImage.Width * dy ] ) )
						// Issue 10 - End
						{
							break;
						}
					}

					dx--;
					dy--;

					// Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert
					tilez = height + ( 3 * m_RoofImage.Data[ p ] ) - 3;
					// Issue 10 - End
					tileid = roofIDs[ p ];

					if ( dx > 0 || dy > 0 )
					{
						tilex = m_BasePoint.X + x;
						tiley = m_BasePoint.Y + y;

						if ( dy > dx )
						{
							tilew = 1;
							tileh = dy + 1;

							while ( dy >= 0 )
							{
								roofIDs[ p + m_RoofImage.Width * dy ] = 0;
								dy--;
							}
						}
						else
						{
							tilew = dx + 1;
							tileh = 1;

							while ( dx >= 0 )
							{
								roofIDs[ p + dx ] = 0;
								dx--;
							}
						}

						x += dx;
						p += dx;
					}
					else
					{
						tilex = m_BasePoint.X + x;
						tiley = m_BasePoint.Y + y;
						tilew = 1;
						tileh = 1;
					}

					// Build command
					string item = string.Format( idFormat, tileid );
					string cmd = string.Format( "TileXYZ {0} {1} {2} {3} {4} {5}",
																					 tilex, tiley, tilew, tileh, tilez, item );
					Pandora.SendToUO( cmd, true );
				}
			}

			return true;
		}
Пример #46
0
        public void TestBasicLockTaken(TestMode testMode)
        {
            using (var conn = Create(testMode))
            {
                var db = conn.GetDatabase(0);
                db.KeyDelete("lock-exists");
                db.StringSet("lock-exists", "old-value", TimeSpan.FromSeconds(20));
                var taken = db.LockTakeAsync("lock-exists", "new-value", TimeSpan.FromSeconds(10));
                var newValue = db.StringGetAsync("lock-exists");
                var ttl = db.KeyTimeToLiveAsync("lock-exists");

                Assert.IsFalse(conn.Wait(taken), "taken");
                Assert.AreEqual("old-value", (string)conn.Wait(newValue));
                var ttlValue = conn.Wait(ttl).Value.TotalSeconds;
                Assert.IsTrue(ttlValue >= 18 && ttlValue <= 20, "ttl");
            }
        }
        //Button - Position Right Pedal
        private void btnPositionRightPedal_MouseUp(object sender, MouseEventArgs e)
        {
            if (CalibrationSettings.Default.SoundEnabled == true) GlobalFunctions.PlayClickSound();
            DisableButtons();

            DataSample.IsPositionOrTestRunning = true;
            DataSample.MaxTorqueRightConc1 = 0;
            lblMaxTorqueConcRight.Text = "0";
            gaugeRight.CircularScales[1].Pointers[0].Value = 0;
            testMode = TestMode.PositionRight;

            if (GlobalVariables.ServoController.InitiateMotor(5, 80, Enumerators.Direction.Forward, GlobalVariables.leftSerialPort).IsSuccess == false)
                return;
            else
            {
                GlobalVariables.leftSerialPort.DiscardInBuffer();
                GlobalVariables.leftSerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
            }
        }
Пример #48
0
        public void TakeLockAndExtend(TestMode mode)
        {
            bool withTran = mode == TestMode.MultiExec;
            using (var conn = Create(mode))
            {
                RedisValue right = Guid.NewGuid().ToString(),
                    wrong = Guid.NewGuid().ToString();

                int DB = mode == TestMode.Twemproxy ? 0 : 7;
                RedisKey Key = "lock-key";

                var db = conn.GetDatabase(DB);

                db.KeyDelete(Key);

                
                var t1 = db.LockTakeAsync(Key, right, TimeSpan.FromSeconds(20));
                var t1b = db.LockTakeAsync(Key, wrong, TimeSpan.FromSeconds(10));
                var t2 = db.LockQueryAsync(Key);
                var t3 = withTran ? db.LockReleaseAsync(Key, wrong) : null;
                var t4 = db.LockQueryAsync(Key);
                var t5 = withTran ? db.LockExtendAsync(Key, wrong, TimeSpan.FromSeconds(60)) : null;
                var t6 = db.LockQueryAsync(Key);
                var t7 = db.KeyTimeToLiveAsync(Key);
                var t8 = db.LockExtendAsync(Key, right, TimeSpan.FromSeconds(60));
                var t9 = db.LockQueryAsync(Key);
                var t10 = db.KeyTimeToLiveAsync(Key);
                var t11 = db.LockReleaseAsync(Key, right);
                var t12 = db.LockQueryAsync(Key);
                var t13 = db.LockTakeAsync(Key, wrong, TimeSpan.FromSeconds(10));
                

                Assert.IsNotNull(right);
                Assert.IsNotNull(wrong);
                Assert.AreNotEqual(right, wrong);
                Assert.IsTrue(conn.Wait(t1), "1");
                Assert.IsFalse(conn.Wait(t1b), "1b");
                Assert.AreEqual(right, conn.Wait(t2), "2");
                if(withTran) Assert.IsFalse(conn.Wait(t3), "3");
                Assert.AreEqual(right, conn.Wait(t4), "4");
                if (withTran) Assert.IsFalse(conn.Wait(t5), "5");
                Assert.AreEqual(right, conn.Wait(t6), "6");
                var ttl = conn.Wait(t7).Value.TotalSeconds;
                Assert.IsTrue(ttl > 0 && ttl <= 20, "7");
                Assert.IsTrue(conn.Wait(t8), "8");
                Assert.AreEqual(right, conn.Wait(t9), "9");
                ttl = conn.Wait(t10).Value.TotalSeconds;
                Assert.IsTrue(ttl > 50 && ttl <= 60, "10");
                Assert.IsTrue(conn.Wait(t11), "11");
                Assert.IsNull((string)conn.Wait(t12), "12");
                Assert.IsTrue(conn.Wait(t13), "13");
            }
        }
Пример #49
0
        public void TestBasicLockNotTaken(TestMode testMode)
        {
            using (var conn = Create(testMode))
            {
                int errorCount = 0;
                conn.ErrorMessage += delegate { Interlocked.Increment(ref errorCount); };
                Task<bool> taken = null;
                Task<RedisValue> newValue = null;
                Task<TimeSpan?> ttl = null;

                const int LOOP = 50;
                var db = conn.GetDatabase(0);
                for (int i = 0; i < LOOP; i++)
                {
                    db.KeyDeleteAsync("lock-not-exists");
                    taken = db.LockTakeAsync("lock-not-exists", "new-value", TimeSpan.FromSeconds(10));
                    newValue = db.StringGetAsync("lock-not-exists");
                    ttl = db.KeyTimeToLiveAsync("lock-not-exists");
                }
                Assert.IsTrue(conn.Wait(taken), "taken");
                Assert.AreEqual("new-value", (string)conn.Wait(newValue));
                var ttlValue = conn.Wait(ttl).Value.TotalSeconds;
                Assert.IsTrue(ttlValue >= 8 && ttlValue <= 10, "ttl");

                Assert.AreEqual(0, errorCount);
            }
        }
Пример #50
0
 private ConnectionMultiplexer Create(TestMode mode)
 {
     switch(mode)
     {
         case TestMode.MultiExec:
             return Create();
         case TestMode.NoMultiExec:
             return Create(disabledCommands: new[] { "multi", "exec" });
         case TestMode.Twemproxy:
             return Create(proxy: Proxy.Twemproxy);
         default:
             throw new NotSupportedException(mode.ToString());
     }
 }
        //Button - Test Right Leg
        private void btnTestRight_MouseUp(object sender, MouseEventArgs e)
        {
            if (CalibrationSettings.Default.SoundEnabled == true) GlobalFunctions.PlayClickSound();
            DisableButtons();

            DataSample.IsPositionOrTestRunning = true;
            DataSample.SelectedTorque = 10;
            DataSample.SelectedSpeed = 5;
            DataSample.MaxTorqueRightConc1 = 0;
            testMode = TestMode.TestRight;

            if (GlobalVariables.ServoController.InitiateMotor(DataSample.SelectedSpeed, DataSample.SelectedTorque, Enumerators.Direction.Backward, GlobalVariables.leftSerialPort).IsSuccess == false)
                return;
            else
            {
                GlobalVariables.leftSerialPort.DiscardInBuffer();
                GlobalVariables.leftSerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
            }
        }
Пример #52
0
 public BoundingVolume(TestMode mode)
 {
     Mode = mode;
 }
Пример #53
0
        public static int Main(string[] args)
        {
            MonoUsbDeviceHandle device_handle = null;

            int r = 0;
            int transferred;
            byte[] testWriteData = new byte[TEST_WRITE_LEN];
            byte[] testReadData = new byte[TEST_READ_LEN];

            if (args.Length > 0)
            {
                switch (args[0].ToLower())
                {
                    case "sync":
                        TEST_MODE = TestMode.Sync;
                        break;
                    case "async":
                        TEST_MODE = TestMode.Async;
                        break;
                }
            }

            fillTestData(testWriteData, TEST_WRITE_LEN);
            memset(testReadData, 0, TEST_READ_LEN);

            int loopCount = 0;
            do
            {
                try
                {
                    do
                    {
                        sessionHandle=new MonoUsbSessionHandle();
                        if (sessionHandle.IsInvalid) throw new Exception("Invalid session handle.");

                        Console.WriteLine("Opening Device..");
                        device_handle = MonoUsbApi.OpenDeviceWithVidPid(sessionHandle, MY_VID, MY_PID);
                        if ((device_handle == null) || device_handle.IsInvalid) break;

                        // If TEST_REST_DEVICE = True, reset the device and re-open
                        if (TEST_REST_DEVICE)
                        {
                            MonoUsbApi.ResetDevice(device_handle);
                            device_handle.Close();
                            device_handle = MonoUsbApi.OpenDeviceWithVidPid(sessionHandle, MY_VID, MY_PID);
                            if ((device_handle == null) || device_handle.IsInvalid) break;
                        }

                        // Set configuration
                        Console.WriteLine("Set Config..");
                        r = MonoUsbApi.SetConfiguration(device_handle, MY_CONFIG);
                        if (r != 0) break;

                        // Claim interface
                        Console.WriteLine("Set Interface..");
                        r = MonoUsbApi.ClaimInterface(device_handle, MY_INTERFACE);
                        if (r != 0) break;

                        /////////////////////
                        // Write test data //
                        /////////////////////
                        int packetCount = 0;
                        int transferredTotal = 0;
                        do
                        {
                            Console.WriteLine("Sending test data..");

                            // If the Async TEST_MODE enumeration is set, use
                            // the internal transfer function
                            if (TEST_MODE == TestMode.Async)
                            {
                                r = (int)doBulkAsyncTransfer(device_handle,
                                                                MY_EP_WRITE,
                                                                testWriteData,
                                                                TEST_WRITE_LEN,
                                                                out transferred,
                                                                MY_TIMEOUT);
                            }
                            else
                            {
                                // Use the sync bulk transfer API function
                                r = MonoUsbApi.BulkTransfer(device_handle,
                                                                       MY_EP_WRITE,
                                                                       testWriteData,
                                                                       TEST_WRITE_LEN,
                                                                       out transferred,
                                                                       MY_TIMEOUT);
                            }
                            if (r == 0)
                            {
                                packetCount++;
                                transferredTotal += transferred;
                            }
                            // Keep writing data until an error occurs or
                            // 4 packets have been sent.
                        } while (r == 0 && packetCount < 5);

                        if (r == (int) MonoUsbError.ErrorTimeout)
                        {
                            // This is considered normal operation
                            Console.WriteLine("Write Timed Out. {0} packet(s) written ({1} bytes)", packetCount, transferredTotal);
                        }
                        else if (r != (int) MonoUsbError.ErrorTimeout && r != 0)
                        {
                            // An error, other than ErrorTimeout was received.
                            Console.WriteLine("Write failed:{0}", (MonoUsbError) r);
                            break;
                        }
                        ////////////////////
                        // Read test data //
                        ////////////////////
                        Console.WriteLine("Reading test data..");
                        packetCount = 0;
                        transferredTotal = 0;
                        do
                        {
                            // If the Async TEST_MODE enumeration is set, use
                            // the internal transfer function
                            if (TEST_MODE == TestMode.Async)
                            {
                                r = (int) doBulkAsyncTransfer(device_handle,
                                                                MY_EP_READ,
                                                                testReadData,
                                                                TEST_READ_LEN,
                                                                out transferred,
                                                                MY_TIMEOUT);
                            }
                            else
                            {
                                // Use the sync bulk transfer API function
                                r = MonoUsbApi.BulkTransfer(device_handle,
                                                                       MY_EP_READ,
                                                                       testReadData,
                                                                       TEST_READ_LEN,
                                                                       out transferred,
                                                                       MY_TIMEOUT);
                            }
                            if (r == (int) MonoUsbError.ErrorTimeout)
                            {
                                // This is considered normal operation
                                Console.WriteLine("Read Timed Out. {0} packet(s) read ({1} bytes)", packetCount, transferredTotal);
                            }
                            else if (r != 0)
                            {
                                // An error, other than ErrorTimeout was received.
                                Console.WriteLine("Read failed:{0}", (MonoUsbError)r);
                            }
                            else
                            {
                                transferredTotal += transferred;
                                packetCount++;

                                // Display test data.
                                Console.Write("Received: ");
                                Console.WriteLine(System.Text.Encoding.Default.GetString(testReadData, 0, transferred));
                            }
                            // Keep reading data until an error occurs, (ErrorTimeout)
                        } while (r == 0);
                    } while (false);
                }
                finally
                {
                    // Free and close resources
                    if (device_handle != null)
                    {
                        if (!device_handle.IsInvalid)
                        {
                            MonoUsbApi.ReleaseInterface(device_handle, MY_INTERFACE);
                            device_handle.Close();
                        }
                    }
                    if (sessionHandle!=null)
                    {
                        sessionHandle.Close();
                        sessionHandle = null;
                    }
                }
                // Run the entire test TEST_LOOP_COUNT times.
            } while (++loopCount < TEST_LOOP_COUNT);

            Console.WriteLine("\nDone!  [Press any key to exit]");
            Console.ReadKey();

            return r;
        }
Пример #54
0
 private void BatchRunConverter(ToolFormat tool, TestMode testMode)
 {
     BatchRunConverter(tool, "*.xml", testMode);
 }
Пример #55
0
 public TestContainerAttribute(Type testedType, TestMode mode, UInt32 milestoneCount, UInt32 iterationCount)
     : this(mode, milestoneCount, iterationCount)
 {
     _testedType = testedType;
 }
Пример #56
0
		private bool Generate( TestMode testmode )
		{
			string seltypename = (string)this.RoofType.SelectedItem;

			foreach ( TileSet ts in this.TileSets )
			{
				if ( seltypename == ts.Name )
				{
					this.tileset = ts;
					break;
				}
			}

			short[] roofids = new short[ this.roofimage.Width * this.roofimage.Height ];
			int i;
			bool fail = false;

			for ( i = 0; i < this.roofimage.Width * this.roofimage.Height; i++ )
			{
				if ( (short)this.roofimage.Data[i] < 0 )
					this.roofimage.Data[i] = (short)( - (short)this.roofimage.Data[i] );
			}
			
			for ( i = 0; i < this.roofimage.Width * this.roofimage.Height ; i++ )
			{
				if ( (short)this.roofimage.Data[i] == (short) 0 )
					roofids[i] = 0;
				else
				{
					uint flags;
					flags =  GetFlags(
						MakeLine( i - this.roofimage.Width ),
						MakeLine( i ),
						MakeLine( i + this.roofimage.Width ) );

					roofids[i] = LookupID(flags);

					if ( roofids[i] == 0 )
					{
						this.roofimage.Data[i] = (short)( - ( (short) this.roofimage.Data[i] ) );
						fail = true;
					}

					if ( testmode != TestMode.NoTest )
					{
						bool corner = !((flags & ~0x88878778) != 0) ||
							!((flags & ~0x88887877) != 0) ||
							!((flags & ~0x77878888) != 0) ||
							!((flags & ~0x87787888) != 0) ||
							!((flags & ~0x87777777) != 0) ||
							!((flags & ~0x77877777) != 0) ||
							!((flags & ~0x77777877) != 0) ||
							!((flags & ~0x77777778) != 0);

						if ( testmode == TestMode.Test && !corner )
							roofids[i] = 0;
						if ( testmode == TestMode.Rest && corner )
							roofids[i] = 0;
					}
				}
			}

			if ( fail )
			{
				// Redraw image
				this.roofimage.MakeBitmap(100, 100);
				this.Preview.Image = this.roofimage.Img;

				if ( MessageBox.Show( this,
					"This tileset cannot generate the roof you requested. Missing pieces are marked in red. Would you like to generate this roof anyway?",
					"Generation failed",
					MessageBoxButtons.YesNo,
					MessageBoxIcon.Question )
					== DialogResult.No )
				{
					return false;
				}
			}

			int j = 0;
			int p = 0;
			int dx;
			int dy = 0;

			int tilex = 0;
			int tiley = 0;
			int tilew = 0;
			int tileh = 0;

			int tilez = 0;
			int tileid = 0;

			string cmd;

			for ( j = 0; j < this.roofimage.Height; j++ )
			{
				for ( i = 0; i < this.roofimage.Width; i++, p++ )
				{
					if ( roofids[p] == 0 )
						continue;

					for ( dx = 1; dx + i < this.roofimage.Width; dx++ )
					{
						if ( ( ((short)roofids[ p + dx ]) != roofids[ p ] ) || ( ((short)roofimage.Data[p]) != ((short)roofimage.Data[p + dx]) ) )
							break;
					}

					for ( dy = 1; dy + j < this.roofimage.Height; dy++ )
					{
						if ( ( ((short)roofids[ p + roofimage.Width * dy ]) != roofids[p] ) || ( ((short) roofimage.Data[p]) != ((short)roofimage.Data[p + roofimage.Width * dy]) ) )
							break;
					}

					dx--;
					dy--;

					tilez = z + ( 3 * (short)roofimage.Data[p] ) - 3;
					tileid = roofids[p];

					if ( ( dx > 0 ) || ( dy > 0 ) )
					{
						tilex = BasePoint.X + i;
						tiley = BasePoint.Y + j;

						if ( dy > dx )
						{
							tilew = 1;
							tileh = dy + 1;

							while ( dy >= 0 )
							{
								roofids[p + roofimage.Width * dy ] = 0;
								dy--;
							}
						}
						else
						{
							tilew = dx + 1;
							tileh = 1;

							while ( dx >= 0 )
							{
								roofids[ p + dx ] = 0;
								dx--;
							}
						}
						i += dx;
						p += dx;
					}
					else
					{
						tilex = BasePoint.X + i;
						tiley = BasePoint.Y + j;
						tilew = 1;
						tileh = 1;
					}

					// Ok now send
					cmd = string.Format( "TileXYZ {0} {1} {2} {3} {4} static {5}\n",
						tilex, tiley, tilew, tileh, tilez, tileid );
					SendToUO( cmd );
				}
			}
			return true;
		}
Пример #57
0
        private void BatchRunConverter(ToolFormat tool, string inputFilter, TestMode testMode)
        {
            var sb = new StringBuilder();

            string toolName = Enum.GetName(typeof(ToolFormat), tool);
            string testDirectory = SarifConverterTests.TestDirectory + "\\" + toolName;
            string[] testFiles = Directory.GetFiles(testDirectory, inputFilter);

            foreach (string file in testFiles)
            {
                RunConverter(sb, tool, file, testMode);
            }

            sb.Length.Should().Be(0, FormatFailureReason(sb, toolName));
        }
Пример #58
0
        private void RunConverter(StringBuilder sb, ToolFormat toolFormat, string inputFileName, TestMode testMode)
        {
            string expectedFileName = inputFileName + ".sarif";
            string generatedFileName = inputFileName + ".actual.sarif";

            try
            {
                this.converter.ConvertToStandardFormat(toolFormat, inputFileName, generatedFileName, ToolFormatConversionOptions.OverwriteExistingOutputFile | ToolFormatConversionOptions.PrettyPrint);
            }
            catch (Exception ex)
            {
                sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "The converter {0} threw an exception for input \"{1}\".", toolFormat, inputFileName));
                sb.AppendLine(ex.ToString());
                return;
            }

            string expectedSarif = File.ReadAllText(expectedFileName);
            string actualSarif = File.ReadAllText(generatedFileName);

            if (expectedSarif == actualSarif)
            {
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ContractResolver = SarifContractResolver.Instance,
                    Formatting = Formatting.Indented
                };

                // Make sure we can successfully deserialize what was just generated
                SarifLog actualLog = JsonConvert.DeserializeObject<SarifLog>(actualSarif, settings);

                actualSarif = JsonConvert.SerializeObject(actualLog, settings);

                bool success;
                switch (testMode)
                {
                    case TestMode.CompareFileContents:
                        success = expectedSarif == actualSarif;
                        break;

                    case TestMode.CompareObjectModels:
                        SarifLog expectedLog = JsonConvert.DeserializeObject<SarifLog>(expectedSarif, settings);
                        success = SarifLogEqualityComparer.Instance.Equals(expectedLog, actualLog);
                        break;

                    default:
                        throw new ArgumentException($"Invalid test mode: {testMode}", nameof(testMode));
                }

                if (success)
                {
                    return;
                }
                else
                {
                    File.WriteAllText(generatedFileName, actualSarif);
                }
            }

            string errorMessage = "The output of the {0} converter did not match for input {1}.";
            sb.AppendLine(string.Format(CultureInfo.CurrentCulture, errorMessage, toolFormat, inputFileName));
            sb.AppendLine("Check differences with:");
            sb.AppendLine(GenerateDiffCommand(expectedFileName, generatedFileName));
        }