public void CreateAndDisposeExplicitSetting(ReferenceHandling referenceHandling)
            {
                var x = new WithSimpleProperties { Value = 1, Time = DateTime.MinValue };
                var y = new WithSimpleProperties { Value = 1, Time = DateTime.MinValue };
                var propertyChanges = new List<string>();
                var expectedChanges = new List<string>();

                using (var tracker = Track.IsDirty(x, y, PropertiesSettings.GetOrCreate(referenceHandling)))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(propertyChanges);

                    x.Value++;
                    Assert.AreEqual(true, tracker.IsDirty);
                    Assert.AreEqual("WithSimpleProperties Value x: 2 y: 1", tracker.Diff.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, propertyChanges);
                }

                x.Value++;
                CollectionAssert.AreEqual(expectedChanges, propertyChanges);

#if (!DEBUG) // debug build keeps instances alive longer for nicer debugging experience
                var wrx = new System.WeakReference(x);
                var wry = new System.WeakReference(y);
                x = null;
                y = null;
                System.GC.Collect();
                Assert.AreEqual(false, wrx.IsAlive);
                Assert.AreEqual(false, wry.IsAlive);
#endif
            }
示例#2
0
        //[Test]
        public void DailyAuditLogs()
        {
            var list = new List<AuditLogDisplay>();
            var merchello = new MerchelloHelper();
            var invoice = merchello.Query.Invoice.GetByKey(new Guid("85F6F194-2F74-4CD5-9CE8-98723B50E719"));
            var _auditLogService = MerchelloContext.Current.Services.AuditLogService;

            if (invoice != null)
            {
                Console.WriteLine("Got an invoice");
                var invoiceLogs = _auditLogService.GetAuditLogsByEntityKey(invoice.Key).Select(x => x.ToAuditLogDisplay()).ToArray();

                if (invoiceLogs.Any()) list.AddRange(invoiceLogs);

                foreach (var orderLogs in invoice.Orders.Select(order => _auditLogService.GetAuditLogsByEntityKey(order.Key).Select(x => x.ToAuditLogDisplay()).ToArray()).Where(orderLogs => orderLogs.Any()))
                {
                    list.AddRange(orderLogs);
                }

                var paymentKeys = MerchelloContext.Current.Services.PaymentService.GetPaymentsByInvoiceKey(invoice.Key).Select(x => x.Key);

                foreach (var paymentLogs in paymentKeys.Select(x => _auditLogService.GetAuditLogsByEntityKey(x).Select(log => log.ToAuditLogDisplay())).ToArray())
                {
                    list.AddRange(paymentLogs);
                }
            }
            Console.WriteLine(JsonConvert.SerializeObject(list.ToSalesHistoryDisplay()));
        }
 private List<LicenseDataGridViewRow> CreateData(int numberThatCanActivate, int numberThatCannotActivate)
 {
     List<LicenseDataGridViewRow> data = new List<LicenseDataGridViewRow>();
     data.AddRange(Enumerable.Repeat(CreateRow(true), numberThatCanActivate));
     data.AddRange(Enumerable.Repeat(CreateRow(false), numberThatCannotActivate));
     return data;
 }
        public void ScopeTextBox()
        {
            var groupBox = this.Window.GetByText<GroupBox>("Scope textbox events");
            var expected = new List<string> { "HasError: False", "Empty" };
            var actual = groupBox.GetMultiple<Label>("Event").Select(x => x.Text).ToArray();
            CollectionAssert.AreEqual(expected, actual, $"Actual: {string.Join(", ", actual.Select(x => "\"" + x + "\""))}");

            var textBox = this.Window.Get<TextBox>("ScopeTextBox");
            textBox.Enter('a');
            this.Window.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.TAB);
            expected.AddRange(new[]
                               {
                                   "ValidationError: Value 'a' could not be converted.",
                                   "HasError: True",
                                   "Action: Added Error: Value 'a' could not be converted. Source: ScopeTextBox OriginalSource: ScopeTextBox"
                               });

            actual = groupBox.GetMultiple<Label>("Event").Select(x => x.Text).ToArray();
            CollectionAssert.AreEqual(expected, actual, $"Actual: {string.Join(", ", actual.Select(x => "\"" + x + "\""))}");

            textBox.Text = "1";
            this.Window.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.TAB);

            expected.AddRange(new[]
                           {
                               "HasError: False",
                               "Empty",
                               "Action: Removed Error: Value 'a' could not be converted. Source: ScopeTextBox OriginalSource: ScopeTextBox"
                           });

            actual = groupBox.GetMultiple<Label>("Event").Select(x => x.Text).ToArray();
            CollectionAssert.AreEqual(expected, actual, $"Actual: {string.Join(", ", actual.Select(x => "\"" + x + "\""))}");
        }
        static IntervalTimePerTimeValuesAttribute()
        {
            var values = new List<IQuantity>();

            var times = new[]
            {
                //TODO: ... however, us, ms, s, min, hr, are not unreasonable to expect ...
                T.Microsecond,
                T.Millisecond,
                T.Second,
                T.Minute,
                T.Hour,
                ////TODO: we do not care about Days or Weeks for purposes of these tests...
                //T.Day,
                //T.Week,
            };

            // TODO: TBD: Avoid scaling too absurdly: may want to be more selective than this...
            var length = times.Length - 2;

            // TODO: TBD: Could also vary the value itself, but this will do for starters...
            const double value = 1e2;

            var first = times.Take(length).ToArray();
            var second = times.Reverse().Take(length).ToArray();

            values.AddRange(from x in first from y in second select new Quantity(value, x, y.Invert()));
            values.AddRange(from y in first from x in second select new Quantity(value, x, y.Invert()));

            Values = values.OfType<object>().ToArray();
        }
            public void AddSameToBoth()
            {
                var x = new ObservableCollection<int>();
                var y = new ObservableCollection<int>();
                var changes = new List<string>();
                var expectedChanges = new List<string>();
                using (var tracker = Track.IsDirty(x, y))
                {
                    tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    CollectionAssert.IsEmpty(changes);

                    x.Add(1);
                    Assert.AreEqual(true, tracker.IsDirty);
                    Assert.AreEqual("ObservableCollection<int> [0] x: 1 y: missing item", tracker.Diff.ToString("", " "));
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, changes);

                    y.Add(1);
                    Assert.AreEqual(false, tracker.IsDirty);
                    Assert.AreEqual(null, tracker.Diff);
                    expectedChanges.AddRange(new[] { "Diff", "IsDirty" });
                    CollectionAssert.AreEqual(expectedChanges, changes);
                }
            }
示例#7
0
        public void should_correctly_read_tile()
        {
            var dummyDescriptor = new TISDescriptor();
            dummyDescriptor.TileDimensions = 2;

            var dummyColour = new TISColour { B = 255, G = 255, R = 255, A = 255 };
            var dummyPalette = new List<TISColour>();
            for (int i = 0; i < 256; i++)
            { dummyPalette.Add(dummyColour); }

            var dummyPixels = new List<byte>();
            for (byte i = 0; i < dummyDescriptor.TileDimensions * 2; i++)
            { dummyPixels.Add(i); }

            var expectedOutput = new TISTile(dummyPalette, dummyPixels, dummyDescriptor.TileDimensions);

            var plugin = new TISPlugin();

            var tileBytes = new List<byte>();
            foreach(var colour in dummyPalette)
            { tileBytes.AddRange(new[] { colour.A, colour.R, colour.G, colour.B }); }
            tileBytes.AddRange(dummyPixels);

            var memoryStream = new MemoryStream(tileBytes.ToArray());
            var binaryReader = new BinaryReader(memoryStream);

            var createTileMethod = plugin.GetType().GetMethod("ReadTile", BindingFlags.NonPublic | BindingFlags.Instance);
            var result = createTileMethod.Invoke(plugin, new object[] { binaryReader, dummyDescriptor });

            Assert.That(result, Is.EqualTo(expectedOutput));
        }
示例#8
0
        public void VerifyExceptionConventions()
        {
            var exceptionTypes = new List<Type>();

            exceptionTypes.AddRange(GetExceptionTypes(typeof(IMessage).Assembly));
            exceptionTypes.AddRange(GetExceptionTypes(typeof(UnicastBus).Assembly));

            foreach (var exceptionType in exceptionTypes)
            {
                if (exceptionType.GetCustomAttribute<ObsoleteAttribute>() !=null )
                {
                    continue;
                }
                Assert.IsTrue(exceptionType.IsPublic, string.Format("Exception '{0}' should be public", exceptionType.Name));
                var constructor = exceptionType.GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);
                Assert.IsNotNull(constructor, string.Format("Exception '{0}' should implement 'protected {0}(SerializationInfo info, StreamingContext context){{}}'", exceptionType.Name));
                var serializableAttribute = exceptionType.GetCustomAttributes(typeof(SerializableAttribute), false).FirstOrDefault();
                Assert.IsNotNull(serializableAttribute, string.Format("Exception '{0}' should have a 'SerializableAttribute'", exceptionType.Name));
                var properties = exceptionType.GetProperties(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly);
                if (properties.Length > 0)
                {
                    var getObjectDataMethod = exceptionType.GetMethod("GetObjectData");
                    Assert.IsTrue(getObjectDataMethod.DeclaringType.Name != "Exception", string.Format("Exception '{0}' has properties and as such should override 'GetObjectData'", exceptionType.Name));
                }
            }
        }
示例#9
0
文件: Visit.cs 项目: havok/ngenerics
        public void Find()
        {
            var list = new List<int>();
            list.AddRange(new[] { 3, 4, 76, 34, 50, 23, 45 });

            var visitor = new ComparableFindingVisitor<int>(50);

            list.AcceptVisitor(visitor);
            Assert.IsTrue(visitor.Found);
            Assert.IsTrue(visitor.HasCompleted);

            visitor = new ComparableFindingVisitor<int>(50);
            list.Clear();
            list.AddRange(new[] { 50, 3, 4, 76, 34, 23, 45 });

            list.AcceptVisitor(visitor);
            Assert.IsTrue(visitor.Found);
            Assert.IsTrue(visitor.HasCompleted);

            visitor = new ComparableFindingVisitor<int>(50);
            list.Clear();
            list.AddRange(new[] { 3, 4, 76, 34, 23, 45, 50 });

            list.AcceptVisitor(visitor);
            Assert.IsTrue(visitor.Found);
            Assert.IsTrue(visitor.HasCompleted);

            visitor = new ComparableFindingVisitor<int>(50);
            list.Clear();
            list.AddRange(new[] { 3, 4, 76, 34, 23, 45 });

            list.AcceptVisitor(visitor);
            Assert.IsFalse(visitor.Found);
            Assert.IsFalse(visitor.HasCompleted);
        }
示例#10
0
		public void TestGetActions()
		{
			IPolicySet policySet = ReadPolicySet(m_testPath + "FileTypesAndActions.policy");

			Assert.AreEqual(1, policySet.Policies.Count);
			IPolicy policy = policySet.Policies[0];

			//Check SMTP channel
			List<CellActionsCollection> collections = ExpressionHelpers.GetActions(policy.Channels[0], policySet, false);

			List<Workshare.Policy.ObjectModel.IAction> actions = new List<Workshare.Policy.ObjectModel.IAction>();

			foreach (CellActionsCollection collection in collections)
				actions.AddRange(collection.Actions);

			Assert.AreEqual(2, actions.Count);

			Assert.AreEqual("Alert Action", actions[0].Name.Value);
			Assert.AreEqual("Block Action", actions[1].Name.Value);

			//Check Active Content channel
			collections = ExpressionHelpers.GetActions(policy.Channels[1], policySet, false);
			actions.Clear();

			foreach (CellActionsCollection collection in collections)
				actions.AddRange(collection.Actions);

			Assert.AreEqual(1, actions.Count);

			Assert.AreEqual("Alert Action", actions[0].Name.Value);
		}
        public void CalculateEquityCurve()
        {
            var deals = new List<MarketOrder>();

            var dealsOpen = TestDataGenerator.GetOpenPosition().Select(LinqToEntity.DecorateOrder).ToList();
            var dealsClose = TestDataGenerator.GetClosePosition().Select(LinqToEntity.DecorateOrder).ToList();

            deals.AddRange(dealsOpen);
            deals.AddRange(dealsClose);

            var transfers = TestDataGenerator.GetBalanceChange().Select(LinqToEntity.DecorateBalanceChange).ToList();
            var firstDealOpenedTime = deals.Min(d => d.TimeEnter);
            transfers.Insert(0, new BalanceChange
                {
                    AccountID = deals[0].AccountID,
                    ValueDate = firstDealOpenedTime.AddHours(-1),
                    CurrencyToDepoRate = 1,
                    ChangeType = BalanceChangeType.Deposit,
                    Amount = 500000
                });

            var dicQuote = new Dictionary<string, List<QuoteData>>();

            foreach (var smb in DalSpot.Instance.GetTickerNames())
                dicQuote.Add(smb, dailyQuoteStorage.GetQuotes(smb).Select(q => new QuoteData(q.b, q.b, q.a)).ToList());

            var quoteArc = new QuoteArchive(dicQuote);
            var res = curveCalculator.CalculateEquityCurve(deals, DepoCurrency, quoteArc, transfers);

            // сверить точку кривой доходности
            CheckEquityCurvePoint(res, transfers, dealsOpen, dealsClose, quoteArc, dicQuote, 0);
            CheckEquityCurvePoint(res, transfers, dealsOpen, dealsClose, quoteArc, dicQuote, 10);
            CheckEquityCurvePoint(res, transfers, dealsOpen, dealsClose, quoteArc, dicQuote, 40);
        }
        public void ObjectMapTest()
        {
            //String[] items = {"camera", "film"};
            //String[] discounts = {"nodiscount", "nodiscount"};

            //PurchaseOrder po = new PurchaseOrder(items, discounts);
            //PurchaseOrder po1 = new PurchaseOrder(items, discounts);
            CustomerTestClass cust = new CustomerTestClass();
            CustomerTestClass cust2 = new CustomerTestClass();
            LocationTestClass theLoc = new LocationTestClass("1", "root location");

            cust.IntVal = 4;
            cust.TheLocation.Description = "first location";
            cust2.TheLocation.Description = "second location";
            cust2.TheLocation.ID = "3";

            Stream mapStream = this.GetType().Assembly.GetManifestResourceStream("Expergent.Tester.ObjectMap.xml");
            StreamReader mapReader = new StreamReader(mapStream);

            ObjectMapTable theTable = new ObjectMapTable(mapReader);

            Agenda agenda = new Agenda();
            List<WME> facts = new List<WME>();
            facts.AddRange(agenda.CreateFactSetFromObjectInstance(new ObjectInstance("CustomerTestClass", cust), theTable));
            facts.AddRange(agenda.CreateFactSetFromObjectInstance(new ObjectInstance("CustomerTestClass", cust2), theTable));
            facts.AddRange(agenda.CreateFactSetFromObjectInstance(new ObjectInstance("LocationTestClass", theLoc), theTable));
            facts.AddRange(agenda.CreateFactSetFromObjectInstance(new ObjectInstance("MyClass", this), theTable));

            Assert.IsTrue(facts.Count == 31, "Wrong # of facts.");
        }
 public void Setup()
 {
     var assembler = new TestRunInfoAssembler();
     var entries = new List<ProfilerEntry>
                       {
                           new ProfilerEntry {Type = ProfileType.Enter, Functionid = 0, Method = "Test1", Runtime = "Test", Sequence = 1, IsTest = true},
                       };
     for (int i = 0; i < 5000; i++)
     {
         entries.AddRange(new[]
                              {
                                  new ProfilerEntry {Type = ProfileType.Enter, Functionid = i + 1, Method = "Method" + i, Runtime = "MethodR" + i, Sequence = 1, IsTest = false},
                              });
     }
     for (int i = 4999; i >=0; i--)
     {
         entries.AddRange(new[]
                              {
                                  new ProfilerEntry {Type = ProfileType.Leave, Functionid = i + 1, Method = "Method" + i, Runtime = "MethodR" + i, Sequence = 1, IsTest = false},
                              });
     }
     entries.AddRange(new[] {
                                new ProfilerEntry {Type = ProfileType.Leave, Functionid = 0, Method = "Test1", Runtime = "Test", Sequence = 5, IsTest = true},
                            });
     items = assembler.Assemble(entries).ToList();
 }
示例#14
0
        public void FixtureSetup()
        {
            //Get files from the standard locations and move them, using file restorer
            List<string> filelocations = new List<string>();

            if (Directory.Exists(LocalPolicyCache.LOCAL_BASEPATH_USER))
                filelocations.AddRange(Directory.GetFiles(LocalPolicyCache.LOCAL_BASEPATH_USER));
            else
            {
                Directory.CreateDirectory(LocalPolicyCache.LOCAL_BASEPATH_USER);
                Assert.IsTrue(Directory.Exists(LocalPolicyCache.LOCAL_BASEPATH_USER), "Failed to set up the folder.  This is a bad thing.");
            }

            if (Directory.Exists(LocalPolicyCache.LOCAL_BASEPATH_COMMON))
                filelocations.AddRange(Directory.GetFiles(LocalPolicyCache.LOCAL_BASEPATH_COMMON));
            else
            {
                Directory.CreateDirectory(LocalPolicyCache.LOCAL_BASEPATH_COMMON);
                Assert.IsTrue(Directory.Exists(LocalPolicyCache.LOCAL_BASEPATH_COMMON), "Failed to set up the folder.  This is a bad thing.");
            }

            foreach (string location in filelocations)
            {
                m_filesToRestore.Add(new FileRestorer(location));
            }
        }
示例#15
0
 private List<Assembly> GetAllAssemblies(string path)
 {
     var files = new List<FileInfo>();
     var directoryToSearch = new DirectoryInfo(path);
     files.AddRange(directoryToSearch.GetFiles("*.dll", SearchOption.AllDirectories));
     files.AddRange(directoryToSearch.GetFiles("*.exe", SearchOption.AllDirectories));
     return files.ConvertAll(file => Assembly.LoadFile(file.FullName));
 }
示例#16
0
		private static List<byte> CreateByteList()
		{
			var byteList = new List<byte>();
			byteList.AddRange(GetTestBytesWithLengthHeader(6));
			byteList.AddRange(GetTestBytesWithLengthHeader(4));
			byteList.AddRange(GetTestBytesWithLengthHeader(10));
			Assert.AreEqual(8+6+12, byteList.Count);
			return byteList;
		}
		public void PrinterConfigTests()
		{
			string staticDataPath = TestContext.CurrentContext.ResolveProjectPath(5, "MatterControl", "StaticData");

			StaticData.Instance = new FileSystemStaticData(staticDataPath);

			var profilesDirectory = new DirectoryInfo(Path.Combine(staticDataPath, "Profiles"));

			foreach (FileInfo file in profilesDirectory.GetFiles("*.printer", SearchOption.AllDirectories))
			{
				var printerSettings = PrinterSettings.LoadFile(file.FullName);

				// Assert that no UserLayer values exist in production .printer files
				Assert.AreEqual(0, printerSettings.UserLayer.Keys.Count, ".printer files should not contain UserLayer values");

				var layersToInspect = new List<PrinterSettingsLayer>();
				layersToInspect.Add(printerSettings.OemLayer);
				layersToInspect.AddRange(printerSettings.MaterialLayers);
				layersToInspect.AddRange(printerSettings.QualityLayers);

				// Validate each PrinterSettingLayer in the .printer file
				foreach (var layer in layersToInspect.Where(l => l.Keys.Any()))
				{
					firstLayerSpeedEqualsAcceptableValue(printerSettings, layer, file.FullName);

					firstLayerHeightLessThanNozzleDiameter(printerSettings, layer, file.FullName);

					layerHeightLessThanNozzleDiameter(printerSettings, layer, file.FullName);

					firstLayerExtrusionWidthAcceptableValue(printerSettings, layer, file.FullName);

					firstLayerExtrusionWidthNotZero(layer, file.FullName);

					bedSizeXYSeparatedByComma(layer, file.FullName);

					printCenterFormatSeparatedByComma(layer, file.FullName);

					testRetractLengthLessThanTwenty(layer, file.FullName);

					testExtruderCountGreaterThanZero(layer, file.FullName);

					minimumFanSpeedLessThanOrEqualToOneHundred(layer, file.FullName);

					maxFanSpeedNotGreaterThanOneHundred(layer, file.FullName);

					noCurlyBracketsInStartGcode(layer, file.FullName);

					noCurlyBracketsInEndGcode(layer, file.FullName);

					testBottomSolidLayersOneMM(layer, file.FullName);

					testFirstLayerTempNotInStartGcode(layer, file.FullName);

					testFirstLayerBedTemperatureNotInStartGcode(layer, file.FullName);
				}
			}
		}
示例#18
0
    public void GetBytesDateTime()
    {
      DateTime dt = new DateTime(2007, 6, 7);
      dt += TimeSpan.FromMilliseconds(24 * 60 * 60 * 1000 - 1);
      List<byte> check = new List<byte>();
      check.AddRange(new byte[] { 0x07, 0x06, 0x07, 0x00 });
      check.AddRange(BitConverter.GetBytes((int) (24*60*60*1000-1)));

      Assert.AreEqual(check.ToArray(), BCDConverter.GetBytes(dt));
    }
示例#19
0
        public void TestChunking()
        {
            List<Int16> data = new List<Int16>();
              data.AddRange(Dirty);
              data.AddRange(Leader);
              data.AddRange(Data);
              data.AddRange(Dirty);
              // Note that this won't be read, as there is no leader.
              data.AddRange(Data);
              data.AddRange(Dirty);
              data.AddRange(Leader);
              data.AddRange(Data);
              data.AddRange(Dirty);
              SoundData audio = new SoundData(data);
              SoundData[] chunks = Analyzer.SplitChunks(audio);
              Assert.AreEqual(2, chunks.Length, "The test should produce 2 chunks.");

              for (int i = 0; i < 2; ++i) {
            IEnumerator<Int16> ie = chunks[i].GetEnumerator();
            for (int j = 0; j < Data.Length; ++j) {
              ie.MoveNext();
              Assert.AreEqual(Data[j], ie.Current);
            }
            Assert.IsFalse(ie.MoveNext());
              }
        }
示例#20
0
		public void ParseEndUserSuppliedXriIdentifer() {
			List<char> symbols = new List<char>(XriIdentifier.GlobalContextSymbols);
			symbols.Add('(');
			List<string> prefixes = new List<string>();
			prefixes.AddRange(symbols.Select(s => s.ToString()));
			prefixes.AddRange(symbols.Select(s => "xri://" + s.ToString()));
			foreach (string prefix in prefixes) {
				var id = Identifier.Parse(prefix + "andrew");
				Assert.IsInstanceOfType(typeof(XriIdentifier), id);
			}
		}
        public void TestMapDocInPortoRecordToDocumentoExternoWithDocumentoIdentity()
        {
            var diprecords = new List<DocumentoInfoArquivoGeral>();
            diprecords.AddRange(DocInPortoRecords.CreateDocInPortoRecordsList3());
            diprecords.AddRange(DocInPortoRecords.CreateDocInPortoRecordsList3());
            var serv = new MockDocInPortoWS();
            var docsExts = serv.ToDocumentosExternos(diprecords, new List<MoradaRecord>());

            Assert.AreEqual(2, docsExts.OfType<DocumentoComposto>().Count());
            Assert.AreEqual(2, docsExts.OfType<DocumentoSimples>().Count());
        }
示例#22
0
        public void TestCustomProtocol()
        {
            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            Random rd = new Random();

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                for (int i = 0; i < 10; i++)
                {
                    List<byte> dataSource = new List<byte>();

                    int messageRepeat = rd.Next(1, 5);

                    StringBuilder sb = new StringBuilder();

                    for (int j = 0; j < messageRepeat; j++)
                    {
                        sb.Append(Guid.NewGuid().ToString().Replace("-", string.Empty));
                    }

                    dataSource.AddRange(m_StartMark);
                    dataSource.AddRange(Encoding.ASCII.GetBytes(sb.ToString(0, rd.Next(20, sb.Length))));
                    dataSource.AddRange(m_EndMark);

                    byte[] data = dataSource.ToArray();

                    if(i % 2 == 0)
                        data[15] = 0x10;
                    else
                        data[15] = 0x1a;

                    socket.Send(data);

                    byte[] response = new byte[5];

                    int read = 0;

                    while (read < response.Length)
                    {
                        read += socket.Receive(response, read, response.Length - read, SocketFlags.None);
                    }

                    Assert.AreEqual(0x54, response[0]);
                    Assert.AreEqual(0x68, response[1]);
                    Assert.AreEqual(0x1a, response[2]);
                    Assert.AreEqual(0x0d, response[3]);
                    Assert.AreEqual(0x0a, response[4]);
                }
            }
        }
        public void VerifyAttributesAreSealed()
        {
            var attributeTypes = new List<Type>();

            attributeTypes.AddRange(GetAttributeTypes(typeof(IMessage).Assembly));
            attributeTypes.AddRange(GetAttributeTypes(typeof(UnicastBus).Assembly));

            foreach (var attributeType in attributeTypes)
            {
                Assert.IsTrue(attributeType.IsSealed, attributeType.FullName+ " should be sealed.");
            }
        }
        public void ShouldDeserializeDictionary()
        {
            var dict = new Dictionary<string, object>();
            dict.Add(SmallCharValue.ToString(), Int64Value);

            var bytes = new List<byte>();
            bytes.Add(UbJsonCommon.ObjectStartMarker);
            bytes.AddRange(SmallCharStringBytes.Skip(1));
            bytes.AddRange(Int64Bytes);
            bytes.Add(UbJsonCommon.ObjectEndMarker);

            Assert.That(_deserializer.Deserialize(bytes.ToArray()), Is.EqualTo(dict));
        }
        public void ShouldDeserializeDictionary()
        {
            var dict = new Dictionary<string, object>();
            dict.Add(SmallCharValue.ToString(), Int64Value);

            var bytes = new List<byte>();
            bytes.Add(UbJsonCommon.ObjectStartMarker);
            bytes.AddRange(SmallCharBytes);  // really this should only be small char string -- but that's for draft 10! for now it's safe, so demo it
            bytes.AddRange(Int64Bytes);
            bytes.Add(UbJsonCommon.ObjectEndMarker);

            Assert.That(_deserializer.Deserialize(bytes.ToArray()), Is.EqualTo(dict));
        }
示例#26
0
        public void DCAwareRoundRobinPolicyTestInParallel()
        {
            byte hostLength = 6;
            var hostList = new List<Host>();
            hostList.AddRange(GetHostList(1, 1, "remote1"));
            hostList.AddRange(GetHostList(1, 1, "remote2"));
            hostList.AddRange(GetHostList((byte)(hostLength - 3)));
            hostList.AddRange(GetHostList(1, 2, "remote1"));

            var clusterMock = new Mock<ICluster>();
            clusterMock
                .Setup(c => c.AllHosts())
                .Returns(hostList);

            //Initialize the balancing policy
            var policy = new DCAwareRoundRobinPolicy("local", 1);
            policy.Initialize(clusterMock.Object);

            Action action = () =>
            {
                var resultingHosts = new List<Host>();
                var hostEnumerator = policy.NewQueryPlan(new SimpleStatement());
                foreach (var h in hostEnumerator)
                {
                    //Slow down to try to execute it at the same time
                    Thread.Sleep(50);
                    resultingHosts.Add(h);
                }
                //The first hosts should be local
                Assert.True(resultingHosts.Take(hostLength-3).All(h => h.Datacenter == "local"));
                //It should return the local hosts first and then 1 per each dc
                Assert.AreEqual(hostLength - 1, resultingHosts.Count);
                Assert.AreEqual(hostLength - 1, resultingHosts.Distinct().Count());
            };

            var actions = new List<Action>();
            for (var i = 0; i < 100; i++)
            {
                actions.Add(action);
            }

            var parallelOptions = new ParallelOptions();
            parallelOptions.TaskScheduler = new ThreadPerTaskScheduler();
            parallelOptions.MaxDegreeOfParallelism = 1000;

            Parallel.Invoke(parallelOptions, actions.ToArray());
            clusterMock.Verify();
        }
示例#27
0
        public void TestReadPersonWithMultiplePendingModificationsActivated()
        {
            // Make a separate copy from the main tree used in other tests
            var tempTree = new FamilySearchFamilyTree(true);
            var features = new List<Feature>();

            tempTree.AuthenticateViaOAuth2Password(Resources.TestUserName, Resources.TestPassword, Resources.TestClientId);

            // Get all the features that are pending
            IRestRequest request = new RedirectableRestRequest()
                .Accept(MediaTypes.APPLICATION_JSON_TYPE)
                .Build("https://sandbox.familysearch.org/platform/pending-modifications", Method.GET);
            IRestResponse response = tempTree.Client.Handle(request);

            // Get each pending feature
            features.AddRange(response.ToIRestResponse<FamilySearchPlatform>().Data.Features);

            // Add every pending feature to the tree's current client
            tempTree.Client.AddFilter(new ExperimentsFilter(features.Select(x => x.Name).ToArray()));

            var state = tempTree.AddPerson(TestBacking.GetCreateMalePerson());
            cleanup.Add(state);

            // Ensure a response came back
            Assert.IsNotNull(state);
            var requestedFeatures = String.Join(",", state.Request.GetHeaders().Get("X-FS-Feature-Tag").Select(x => x.Value.ToString()));
            // Ensure each requested feature was found in the request headers
            Assert.IsTrue(features.TrueForAll(x => requestedFeatures.Contains(x.Name)));
        }
示例#28
0
        public void PickRemaining()
        {
            other.BitField.SetAll(true);
            other.IsChoking = false;
            List<Block> allBlocks = new List<Block>();
            pieces.ForEach(delegate(Piece p) { allBlocks.AddRange(p.Blocks); });
            allBlocks.RemoveAll(delegate(Block b){ return alreadyGot.Contains(b);});
            RequestMessage m;
            while ((m = picker.PickPiece(other, new List<PeerId>())) != null)
            {
                if(alreadyGot.Exists(delegate(Block b){
                    return b.PieceIndex == m.PieceIndex &&
                           b.StartOffset == m.StartOffset &&
                           b.RequestLength == m.RequestLength;}))
                {
                    Assert.AreEqual(0, allBlocks.Count, "#1");
                    break;
                }
                int ret = allBlocks.RemoveAll(delegate (Block b) {
                    return b.PieceIndex == m.PieceIndex &&
                           b.StartOffset == m.StartOffset &&
                           b.RequestLength == m.RequestLength;
                });
                Assert.AreEqual(1, ret, "#2");

            }
        }
示例#29
0
        public void ShouldTellUsIfItCantHelp()
        {
            // Given a group with no duplicated actuals but potentially empty cells
            var cellsWithActuals = CreateCellsWithActuals(2, 3, 4, 5, 6, 7);
            var cellsWithout = new List<Cell> {new Cell(new CellId(-1, -1)), new Cell(new CellId(-1, -1)), new Cell(new CellId(-1, -1))};

            // When we ask the rule to help
            var rule = new ActualsCollide();
            var cells = new List<Cell>();
            cells.AddRange(cellsWithActuals);
            cells.AddRange(cellsWithout);
            var hint = rule.HelpWith(cells);

            // Then it should tell us it can't help
            Assert.AreEqual(Hint.None, hint);
        }
示例#30
0
        private static List<string> GetNonCompliantFilesForDirectory(string directory)
        {
            string directoryName = new DirectoryInfo(directory).Name;

            // Ignore bin, obj, Resources, and svn directories
            if ((directoryName == "obj") ||
                (directoryName == "bin") ||
                (directoryName == ".svn") ||
                (directoryName == "Resources")) {
                return new List<string>();
            }

            var ret = new List<string>();

            foreach (string file in Directory.GetFiles(directory, "*.cs")) {
                // Ignore designer files
                if (file.Contains(".Designer.cs")) {
                    continue;
                }

                if (!IsCopyrightHeaderInFile(file)) {
                    ret.Add(Path.GetFullPath(file));
                }
            }

            foreach (string subdirectory in Directory.GetDirectories(directory)) {
                ret.AddRange(GetNonCompliantFiles(subdirectory));
            }

            return ret;
        }