private static void CreateRandomUdpPayload(Random random, UdpLayer udpLayer, List<ILayer> layers) { if (random.NextBool(20)) { // Finish with payload. PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100)); layers.Add(payloadLayer); return; } DnsLayer dnsLayer = random.NextDnsLayer(); layers.Add(dnsLayer); ushort specialPort = (ushort)(random.NextBool() ? 53 : 5355); if (dnsLayer.IsQuery) udpLayer.DestinationPort = specialPort; else udpLayer.SourcePort = specialPort; }
public static void RotateToPoint(this ITransform trans, GridLocation loc, System.Random rand) { switch (loc) { case GridLocation.RIGHT: case GridLocation.LEFT: trans.YRotation = rand.NextBool() ? -90 : 90; break; case GridLocation.TOPRIGHT: case GridLocation.BOTTOMLEFT: trans.YRotation = rand.NextBool() ? 45 : -135; break; case GridLocation.BOTTOMRIGHT: case GridLocation.TOPLEFT: trans.YRotation = rand.NextBool() ? -45 : 135; break; case GridLocation.BOTTOM: case GridLocation.TOP: trans.YRotation = rand.NextBool() ? 0 : 180; break; } }
private void CheckIntersectionCore(int capacity, Random r) { BitVector b1 = BitVector.Empty, b2 = BitVector.Empty; b1.EnsureCapacity(capacity); b2.EnsureCapacity(capacity); bool[] a1 = new bool[capacity], a2 = new bool[capacity]; for (int i = 0; i < capacity; i++) { b1[i] = a1[i] = r.NextBool(); b2[i] = a2[i] = r.NextBool(); } bool changed = b1.IntersectWith(b2); bool changed2 = false; for (int i = 0; i < capacity; i++) { bool a = a1[i]; a1[i] &= a2[i]; changed2 |= (a != a1[i]); } for (int i = 0; i < capacity; i++) { Assert.Equal(a1[i], b1[i]); } Assert.Equal(changed, changed2); }
public PandaStats CreateChildStats(PandaStats father, PandaStats mother) { _random = new Random(_createdPandasCount++); Assert.IsTrue(father.Genotype.Count == mother.Genotype.Count); var newGenotype = DrawSingleValuesAndMutate(father.Genotype) .Join(DrawSingleValuesAndMutate(mother.Genotype), c => c.Trait, c => c.Trait, (fatherGene, motherGene) => new Gene() { FatherGene = fatherGene.Value, MotherGene = motherGene.Value, Trait = fatherGene.Trait }) .ToList(); Phenotype newPhenotype = CreatePhenotype(newGenotype); var gender = _random.NextBool() ? Gender.Male : Gender.Female; return(new PandaStats() { name = $"Panda No:{_createdPandasCount}", birthdate = _createdPandasCount, gender = gender, Genotype = newGenotype, Phenotype = newPhenotype }); }
private static void TestRandom() { long time = DateTime.Now.Ticks; Random rand = new Random(); int t = 0, f = 0; for (int i = 0; i < 10000; i++) { bool b = rand.NextBool(); if (b) { t++; } else { f++; } } VersatileIO.WriteComplex("&aTRUE: {0}\n&cFALSE: {1}".Fmt(t, f), '&'); long elapsedTicks = DateTime.Now.Ticks - time; TimeSpan dtime = TimeSpan.FromTicks(elapsedTicks); VersatileIO.WriteLine("Elapsed time: {0} ms".Fmt(dtime.TotalMilliseconds)); }
public void RandomUdpTest() { EthernetLayer ethernetLayer = new EthernetLayer { Source = new MacAddress("00:01:02:03:04:05"), Destination = new MacAddress("A0:A1:A2:A3:A4:A5") }; int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 1000; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(null); ipV4Layer.HeaderChecksum = null; IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Udp, false); EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6; Layer ipLayer = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer); UdpLayer udpLayer = random.NextUdpLayer(); udpLayer.Checksum = null; PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000)); Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, udpLayer, payloadLayer); Assert.IsTrue(packet.IsValid, "IsValid"); // Ethernet ethernetLayer.EtherType = ethernetType; Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer"); ethernetLayer.EtherType = EthernetType.None; // Ip if (ipLayer == ipV4Layer) { // IpV4. ipV4Layer.Protocol = IpV4Protocol.Udp; ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum; Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer"); ipV4Layer.HeaderChecksum = null; } else { // IpV6. Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IP Layer"); } // UDP udpLayer.Checksum = packet.Ethernet.Ip.Udp.Checksum; Assert.AreEqual(udpLayer, packet.Ethernet.Ip.Udp.ExtractLayer(), "UDP Layer"); Assert.AreEqual(UdpDatagram.HeaderLength + payloadLayer.Length, packet.Ethernet.Ip.Udp.TotalLength, "Total Length"); Assert.IsTrue(!udpLayer.CalculateChecksum && packet.Ethernet.Ip.Udp.Checksum == 0 || udpLayer.CalculateChecksum && packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect"); Assert.IsTrue(packet.Ethernet.Ip.Udp.IsChecksumOptional, "IsChecksumOptional"); Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Udp.Payload, "Payload"); } }
public static decimal NextDecimal(this System.Random generator) => new decimal( generator.NextInt(), generator.NextInt(), generator.NextInt(), generator.NextBool(), generator.NextByte() );
/// <summary> Returns randomly a number or another cell reference </summary> private static string RndVar(System.Random random, DataStore <CellsModel> store) { if (random.NextBool()) { return("" + random.Next(-10, 10)); } // With 50% prob. return a random other cell reference, currently in use: return("" + random.NextRndChild(store.GetState().cells).Key); }
public void initGene() { for (int x = 0; x < gene.Length; x++) { gene[x] = rnd.NextBool(); // gene[x] = true; } gene[gene.Length - 2] = false; }
public void RandomDnsTest() { EthernetLayer ethernetLayer = new EthernetLayer { Source = new MacAddress("00:01:02:03:04:05"), Destination = new MacAddress("A0:A1:A2:A3:A4:A5") }; int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 1000; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(null); ipV4Layer.HeaderChecksum = null; Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(true); UdpLayer udpLayer = random.NextUdpLayer(); udpLayer.Checksum = null; DnsLayer dnsLayer; do { dnsLayer = random.NextDnsLayer(); } while (dnsLayer.Length > 65000 - ipLayer.Length); Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, udpLayer, dnsLayer); Assert.IsTrue(packet.IsValid, "IsValid"); // DNS DnsLayer actualLayer = (DnsLayer)packet.Ethernet.Ip.Udp.Dns.ExtractLayer(); Assert.AreEqual(dnsLayer, actualLayer, "DNS Layer"); Assert.IsTrue(packet.Ethernet.Ip.Udp.Dns.IsValid); DnsDataResourceRecord opt = packet.Ethernet.Ip.Udp.Dns.Additionals.FirstOrDefault(additional => additional.DnsType == DnsType.Opt); Assert.AreEqual(opt, packet.Ethernet.Ip.Udp.Dns.OptionsRecord); foreach (var record in packet.Ethernet.Ip.Udp.Dns.ResourceRecords) { Assert.IsTrue(record.Equals(record)); Assert.IsTrue(record.DomainName.Equals((object)record.DomainName)); Assert.IsTrue(record.DomainName.Equals((object)record.DomainName)); Assert.AreEqual(record.GetHashCode(), record.GetHashCode()); } foreach (var record in packet.Ethernet.Ip.Udp.Dns.DataResourceRecords) { MoreAssert.IsBiggerOrEqual(9, record.ToString().Length); Assert.IsTrue(record.Equals((object)record)); Assert.IsInstanceOfType(record.Data, DnsResourceData.GetDnsResourceDataType(record.DnsType) ?? typeof(DnsResourceDataAnything)); Assert.IsTrue(record.DomainName.Equals((object)record.DomainName)); Assert.IsFalse(record.Data.Equals(null)); } } }
public Island(Vector2 location, Random random) { Location = location; Effects = random.NextBool() ? SpriteEffects.None : SpriteEffects.FlipHorizontally; Texture = IslandsCurses.Textures["island"]; Ratio = new Vector2(random.NextRatio(60) * (IslandSpace.X / Texture.Width), random.NextRatio(60) * (IslandSpace.Y / Texture.Width)); Status = Status.Normal; }
private void CheckRandomDataCore(Random r1, Random r2, int capacity) { BitVector d = BitVector.Create(capacity); Assert.Equal(capacity, d.Capacity); for (int i1 = 0; i1 < capacity; i1++) d[i1] = r1.NextBool(); Assert.Equal(capacity, d.Capacity); for (int i2 = 0; i2 < capacity; i2++) Assert.Equal(d[i2], r2.NextBool()); }
public static void RotateToPoint(this ITransform trans, GridDirection dir, System.Random rand) { switch (dir) { case GridDirection.HORIZ: trans.YRotation = rand.NextBool() ? 90 : -90; break; case GridDirection.VERT: trans.YRotation = rand.NextBool() ? 180 : 0; break; case GridDirection.DIAGTLBR: trans.YRotation = rand.NextBool() ? -45 : 135; break; case GridDirection.DIAGBLTR: trans.YRotation = rand.NextBool() ? 45 : -135; break; } }
public static object Next(this System.Random generator, Type desired) { switch (Type.GetTypeCode(desired)) { case TypeCode.Boolean: return(generator.NextBool()); case TypeCode.Byte: return(generator.NextByte()); case TypeCode.Char: return(generator.NextChar()); case TypeCode.DateTime: return(generator.NextDateTime()); case TypeCode.Decimal: return(generator.NextDecimal()); case TypeCode.Double: return(generator.NextDouble()); case TypeCode.Int16: return(generator.NextShort()); case TypeCode.Int32: return(generator.NextInt()); case TypeCode.Int64: return(generator.NextLong()); case TypeCode.SByte: return(generator.NextSByte()); case TypeCode.Single: return(generator.NextFloat()); case TypeCode.UInt16: return(generator.NextUShort()); case TypeCode.UInt32: return(generator.NextUInt()); case TypeCode.UInt64: return(generator.NextULong()); default: throw new ArgumentOutOfRangeException("Cannot provide a random " + desired); } }
public void Merge8BoolRandomTest() { Random random = new Random(); for (int i = 0; i != 10; ++i) { byte expectedResult = 0; bool[] input = new bool[8]; for (int bit = 0; bit != 8; ++bit) { bool bitValue = random.NextBool(); input[bit] = bitValue; expectedResult <<= 1; if (bitValue) ++expectedResult; } Assert.AreEqual(expectedResult, BitSequence.Merge(input[0], input[1], input[2], input[3], input[4], input[5], input[6], input[7])); } }
/// <summary> /// Returns a SELECT command that retrieves data from a table /// </summary> private String GetSelectCommandForMultipleRows(Random rnd, DbCommand com, TableMetadata inputTable, bool isXml) { int rowcount = rnd.Next(Depth); StringBuilder cmdText = new StringBuilder(); cmdText.Append("SELECT TOP "); cmdText.Append(rowcount); //Jonfo added this to prevent table scan of 75k row tables cmdText.Append(" PrimaryKey"); List<TableColumn> columns = inputTable.Columns; int colindex = rnd.Next(0, columns.Count); for (int i = 0; i <= colindex; i++) { if (columns[i].ColumnName == "PrimaryKey") continue; cmdText.Append(", "); cmdText.Append(columns[i].ColumnName); } cmdText.Append(" FROM \""); cmdText.Append(inputTable.TableName); cmdText.Append("\" WITH(NOLOCK) WHERE PrimaryKey "); // We randomly pick an operator from '>' or '=' to allow for randomization // of possible rows returned by this query. This approach *may* help // in reducing the likelihood of multiple threads accessing same rows. // If multiple threads access same rows, there may be locking issues // which may be avoided because of this randomization. string op = rnd.NextBool() ? ">" : "="; cmdText.Append(op).Append(" "); string pName = GetParameterName("P0"); cmdText.Append(pName); DbParameter param = DbFactory.CreateParameter(); param.ParameterName = pName; param.Value = GetRandomPK(rnd, inputTable); param.DbType = DbType.Int32; com.Parameters.Add(param); return cmdText.ToString(); }
private DbCommand CreateCommand(Random rnd, DataStressConnection conn) { DbCommand cmd; if (conn == null) { cmd = DbFactory.CreateCommand(); } else { cmd = conn.CreateCommand(); } if (rnd != null) { cmd.CommandTimeout = rnd.NextBool() ? 30 : 600; } return cmd; }
public void RandomHttpTest() { int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 200; ++i) { EthernetLayer ethernetLayer = random.NextEthernetLayer(EthernetType.None); IpV4Layer ipV4Layer = random.NextIpV4Layer(null); ipV4Layer.HeaderChecksum = null; Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(true); TcpLayer tcpLayer = random.NextTcpLayer(); tcpLayer.Checksum = null; HttpLayer httpLayer = random.NextHttpLayer(); Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, tcpLayer, httpLayer); Assert.IsTrue(packet.IsValid, "IsValid"); HttpDatagram httpDatagram = packet.Ethernet.Ip.Tcp.Http; Assert.AreEqual(httpLayer.Version, httpDatagram.Version); if (httpLayer.Version != null) Assert.AreEqual(httpLayer.Version.GetHashCode(), httpDatagram.Version.GetHashCode()); if (httpLayer is HttpRequestLayer) { Assert.IsTrue(httpDatagram.IsRequest); Assert.IsTrue(httpLayer.IsRequest); Assert.IsFalse(httpDatagram.IsResponse); Assert.IsFalse(httpLayer.IsResponse); HttpRequestLayer httpRequestLayer = (HttpRequestLayer)httpLayer; HttpRequestDatagram httpRequestDatagram = (HttpRequestDatagram)httpDatagram; Assert.AreEqual(httpRequestLayer.Method, httpRequestDatagram.Method); if (httpRequestLayer.Method != null) { Assert.AreEqual(httpRequestLayer.Method.GetHashCode(), httpRequestDatagram.Method.GetHashCode()); Assert.AreEqual(httpRequestLayer.Method.KnownMethod, httpRequestDatagram.Method.KnownMethod); } Assert.AreEqual(httpRequestLayer.Uri, httpRequestDatagram.Uri); } else { Assert.IsFalse(httpDatagram.IsRequest); Assert.IsFalse(httpLayer.IsRequest); Assert.IsTrue(httpDatagram.IsResponse); Assert.IsTrue(httpLayer.IsResponse); HttpResponseLayer httpResponseLayer = (HttpResponseLayer)httpLayer; HttpResponseDatagram httpResponseDatagram = (HttpResponseDatagram)httpDatagram; Assert.AreEqual(httpResponseLayer.StatusCode, httpResponseDatagram.StatusCode); Assert.AreEqual(httpResponseLayer.ReasonPhrase, httpResponseDatagram.ReasonPhrase); } Assert.AreEqual(httpLayer.Header, httpDatagram.Header); if (httpLayer.Header != null) { Assert.AreEqual(httpLayer.Header.GetHashCode(), httpDatagram.Header.GetHashCode()); foreach (var field in httpLayer.Header) Assert.IsFalse(field.Equals("abc")); foreach (var field in (IEnumerable)httpLayer.Header) Assert.IsFalse(field.Equals("abc")); MoreAssert.AreSequenceEqual(httpLayer.Header.Select(field => field.GetHashCode()), httpDatagram.Header.Select(field => field.GetHashCode())); if (httpLayer.Header.ContentType != null) { var parameters = httpLayer.Header.ContentType.Parameters; Assert.IsNotNull(((IEnumerable)parameters).GetEnumerator()); Assert.AreEqual<object>(parameters, httpDatagram.Header.ContentType.Parameters); Assert.AreEqual(parameters.GetHashCode(), httpDatagram.Header.ContentType.Parameters.GetHashCode()); Assert.AreEqual(parameters.Count, httpDatagram.Header.ContentType.Parameters.Count); int maxParameterNameLength = parameters.Any() ? parameters.Max(pair => pair.Key.Length) : 0; Assert.IsNull(parameters[new string('a', maxParameterNameLength + 1)]); } } Assert.AreEqual(httpLayer.Body, httpDatagram.Body); Assert.AreEqual(httpLayer, httpDatagram.ExtractLayer(), "HTTP Layer"); Assert.AreEqual(httpLayer.Length, httpDatagram.Length); } }
private static void CreateRandomTcpPayload(Random random, TcpLayer tcpLayer, List<ILayer> layers) { if (random.NextBool(20)) { // Finish with payload. PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100)); layers.Add(payloadLayer); return; } HttpLayer httpLayer = random.NextHttpLayer(); layers.Add(httpLayer); if (httpLayer.IsRequest) tcpLayer.DestinationPort = 80; else tcpLayer.SourcePort = 80; if (random.NextBool()) return; HttpLayer httpLayer2 = httpLayer.IsRequest ? (HttpLayer)random.NextHttpRequestLayer() : random.NextHttpResponseLayer(); layers.Add(httpLayer2); }
public void RandomIgmpTest() { EthernetLayer ethernetLayer = new EthernetLayer { Source = new MacAddress("00:01:02:03:04:05"), Destination = new MacAddress("A0:A1:A2:A3:A4:A5") }; int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 200; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(null); ipV4Layer.HeaderChecksum = null; Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.InternetGroupManagementProtocol, false); IgmpLayer igmpLayer = random.NextIgmpLayer(); Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, igmpLayer); Assert.IsTrue(packet.IsValid, "IsValid"); // Ethernet ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6; Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer"); ethernetLayer.EtherType = EthernetType.None; // IP. if (ipV4Layer == ipLayer) { // IPv4. ipV4Layer.Protocol = IpV4Protocol.InternetGroupManagementProtocol; ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum; Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer"); ipV4Layer.HeaderChecksum = null; } else { // IPv6. Assert.AreEqual(ipLayer, packet.Ethernet.IpV6.ExtractLayer(), "IPv6 Layer"); } // IGMP Assert.IsTrue(packet.Ethernet.Ip.Igmp.IsChecksumCorrect); Assert.AreEqual(igmpLayer, packet.Ethernet.Ip.Igmp.ExtractLayer(), "IGMP Layer"); Assert.AreEqual(igmpLayer.GetHashCode(), packet.Ethernet.Ip.Igmp.ExtractLayer().GetHashCode(), "IGMP Layer"); Assert.AreNotEqual(igmpLayer, null); Assert.AreNotEqual(igmpLayer, random.NextPayloadLayer(igmpLayer.Length)); Assert.AreNotEqual(igmpLayer.GetHashCode(), random.NextPayloadLayer(igmpLayer.Length).GetHashCode()); if (packet.Ethernet.Ip.Igmp.QueryVersion != IgmpQueryVersion.Version3) MoreAssert.IsSmallerOrEqual(IgmpDatagram.MaxMaxResponseTime, packet.Ethernet.Ip.Igmp.MaxResponseTime); if (packet.Ethernet.Ip.Igmp.MessageType != IgmpMessageType.MembershipQuery) Assert.AreEqual(IgmpQueryVersion.None, packet.Ethernet.Ip.Igmp.QueryVersion); switch (igmpLayer.MessageTypeValue) { case IgmpMessageType.CreateGroupRequestVersion0: case IgmpMessageType.CreateGroupReplyVersion0: case IgmpMessageType.JoinGroupRequestVersion0: case IgmpMessageType.JoinGroupReplyVersion0: case IgmpMessageType.LeaveGroupRequestVersion0: case IgmpMessageType.LeaveGroupReplyVersion0: case IgmpMessageType.ConfirmGroupRequestVersion0: case IgmpMessageType.ConfirmGroupReplyVersion0: Assert.AreEqual(0, packet.Ethernet.Ip.Igmp.Version); IgmpVersion0Layer igmpVersion0Layer = (IgmpVersion0Layer)igmpLayer; Assert.AreEqual(igmpVersion0Layer.IdentifierValue, packet.Ethernet.Ip.Igmp.Identifier); Assert.AreEqual(igmpVersion0Layer.AccessKeyValue, packet.Ethernet.Ip.Igmp.AccessKey); switch (igmpLayer.MessageTypeValue) { case IgmpMessageType.CreateGroupRequestVersion0: Assert.AreEqual(((IgmpCreateGroupRequestVersion0Layer)igmpLayer).CreateGroupRequestCode, packet.Ethernet.Ip.Igmp.CreateGroupRequestCode); break; case IgmpMessageType.CreateGroupReplyVersion0: case IgmpMessageType.JoinGroupReplyVersion0: case IgmpMessageType.LeaveGroupReplyVersion0: case IgmpMessageType.ConfirmGroupReplyVersion0: IgmpReplyVersion0Layer igmpReplyVersion0Layer = (IgmpReplyVersion0Layer)igmpVersion0Layer; Assert.AreEqual(igmpReplyVersion0Layer.Code, packet.Ethernet.Ip.Igmp.ReplyCode); if (packet.Ethernet.Ip.Igmp.ReplyCode == IgmpVersion0ReplyCode.RequestPendingRetryInThisManySeconds) Assert.AreEqual(igmpReplyVersion0Layer.RetryInThisManySeconds, packet.Ethernet.Ip.Igmp.RetryInThisManySeconds); break; } break; case IgmpMessageType.MembershipQuery: switch (igmpLayer.QueryVersion) { case IgmpQueryVersion.Version1: Assert.AreEqual(1, packet.Ethernet.Ip.Igmp.Version); break; case IgmpQueryVersion.Version2: Assert.AreEqual(2, packet.Ethernet.Ip.Igmp.Version); break; case IgmpQueryVersion.Version3: Assert.AreEqual(3, packet.Ethernet.Ip.Igmp.Version); break; default: Assert.Fail(igmpLayer.QueryVersion.ToString()); break; } break; case IgmpMessageType.MembershipReportVersion1: Assert.AreEqual(1, packet.Ethernet.Ip.Igmp.Version); break; case IgmpMessageType.MembershipReportVersion2: case IgmpMessageType.LeaveGroupVersion2: Assert.AreEqual(2, packet.Ethernet.Ip.Igmp.Version); break; case IgmpMessageType.MembershipReportVersion3: Assert.AreEqual(3, packet.Ethernet.Ip.Igmp.Version); break; default: Assert.Fail(igmpLayer.MessageTypeValue.ToString()); break; } foreach (IgmpGroupRecordDatagram groupRecord in packet.Ethernet.Ip.Igmp.GroupRecords) Assert.IsNotNull(groupRecord.ToString()); } }
public static int NextNegative(this System.Random rand) { return(rand.NextBool() ? -1 : 1); }
public bool ShouldModifySession(Random rnd) { // 33% of the time, we want to modify the user session on the server return rnd.NextBool(.33); }
public void RandomGreTest() { EthernetLayer ethernetLayer = new EthernetLayer { Source = new MacAddress("00:01:02:03:04:05"), Destination = new MacAddress("A0:A1:A2:A3:A4:A5") }; int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 200; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(null); ipV4Layer.HeaderChecksum = null; Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false); GreLayer greLayer = random.NextGreLayer(); PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100)); PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer, payloadLayer); Packet packet = packetBuilder.Build(DateTime.Now); if (greLayer.Checksum == null && !new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(packet.Ethernet.Ip.Gre.ProtocolType)) { Assert.IsTrue(packet.IsValid, "IsValid, ProtocolType=" + packet.Ethernet.Ip.Gre.ProtocolType); } // Ethernet ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6; Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer"); ethernetLayer.EtherType = EthernetType.None; // IP. if (ipLayer == ipV4Layer) { // IPv4. ipV4Layer.Protocol = IpV4Protocol.Gre; ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.Ip.ExtractLayer()).HeaderChecksum; Assert.AreEqual(ipV4Layer, packet.Ethernet.Ip.ExtractLayer()); ipV4Layer.HeaderChecksum = null; Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength); Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect); Assert.AreEqual(ipV4Layer.Length + greLayer.Length + payloadLayer.Length, packet.Ethernet.Ip.TotalLength); Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.Ip.Version); } else { // IPv6. Assert.AreEqual(ipLayer, packet.Ethernet.Ip.ExtractLayer()); } // GRE GreDatagram actualGre = packet.Ethernet.Ip.Gre; GreLayer actualGreLayer = (GreLayer)actualGre.ExtractLayer(); if (greLayer.ChecksumPresent && greLayer.Checksum == null) { Assert.IsTrue(actualGre.IsChecksumCorrect); greLayer.Checksum = actualGre.Checksum; } Assert.AreEqual(greLayer, actualGreLayer, "Layer"); if (actualGreLayer.Key != null) actualGreLayer.SetKey(actualGreLayer.KeyPayloadLength.Value, actualGreLayer.KeyCallId.Value); else { Assert.IsNull(actualGreLayer.KeyPayloadLength); Assert.IsNull(actualGreLayer.KeyCallId); } Assert.AreEqual(greLayer, actualGreLayer, "Layer"); if (actualGre.KeyPresent) { Assert.AreEqual(greLayer.KeyPayloadLength, actualGre.KeyPayloadLength, "KeyPayloadLength"); Assert.AreEqual(greLayer.KeyCallId, actualGre.KeyCallId, "KeyCallId"); } Assert.AreNotEqual(random.NextGreLayer(), actualGreLayer, "Not Layer"); Assert.AreEqual(greLayer.Length, actualGre.HeaderLength); Assert.IsTrue(actualGre.KeyPresent ^ (greLayer.Key == null)); MoreAssert.IsSmaller(8, actualGre.RecursionControl); MoreAssert.IsSmaller(32, actualGre.FutureUseBits); Assert.IsTrue(actualGre.RoutingPresent ^ (greLayer.Routing == null && greLayer.RoutingOffset == null)); Assert.IsTrue(actualGre.SequenceNumberPresent ^ (greLayer.SequenceNumber == null)); Assert.IsTrue(!actualGre.StrictSourceRoute || actualGre.RoutingPresent); if (actualGre.RoutingPresent) { Assert.IsNotNull(actualGre.ActiveSourceRouteEntryIndex); if (actualGre.ActiveSourceRouteEntryIndex < actualGre.Routing.Count) Assert.IsNotNull(actualGre.ActiveSourceRouteEntry); foreach (GreSourceRouteEntry entry in actualGre.Routing) { Assert.AreNotEqual(entry, 2); Assert.AreEqual(entry.GetHashCode(), entry.GetHashCode()); switch (entry.AddressFamily) { case GreSourceRouteEntryAddressFamily.AsSourceRoute: GreSourceRouteEntryAs asEntry = (GreSourceRouteEntryAs)entry; MoreAssert.IsInRange(0, asEntry.AsNumbers.Count, asEntry.NextAsNumberIndex); if (asEntry.NextAsNumberIndex != asEntry.AsNumbers.Count) Assert.AreEqual(asEntry.AsNumbers[asEntry.NextAsNumberIndex], asEntry.NextAsNumber); break; case GreSourceRouteEntryAddressFamily.IpSourceRoute: GreSourceRouteEntryIp ipEntry = (GreSourceRouteEntryIp)entry; MoreAssert.IsInRange(0, ipEntry.Addresses.Count, ipEntry.NextAddressIndex); if (ipEntry.NextAddressIndex != ipEntry.Addresses.Count) Assert.AreEqual(ipEntry.Addresses[ipEntry.NextAddressIndex], ipEntry.NextAddress); break; default: GreSourceRouteEntryUnknown unknownEntry = (GreSourceRouteEntryUnknown)entry; MoreAssert.IsInRange(0, unknownEntry.Data.Length, unknownEntry.PayloadOffset); break; } } } else { Assert.IsNull(actualGre.ActiveSourceRouteEntry); } Assert.IsNotNull(actualGre.Payload); switch (actualGre.ProtocolType) { case EthernetType.IpV4: Assert.IsNotNull(actualGre.IpV4); break; case EthernetType.Arp: Assert.IsNotNull(actualGre.Arp); break; } } }
public void InvalidGreTest() { EthernetLayer ethernetLayer = new EthernetLayer { Source = new MacAddress("00:01:02:03:04:05"), Destination = new MacAddress("A0:A1:A2:A3:A4:A5") }; int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 100; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(IpV4Protocol.Gre); ipV4Layer.HeaderChecksum = null; Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.Gre, false); GreLayer greLayer = random.NextGreLayer(); greLayer.Checksum = null; greLayer.Routing = new List<GreSourceRouteEntry> { new GreSourceRouteEntryAs(new List<ushort> {123}.AsReadOnly(), 0), new GreSourceRouteEntryIp(new List<IpV4Address> {random.NextIpV4Address()}.AsReadOnly(), 0) }.AsReadOnly(); PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, greLayer); Packet packet = packetBuilder.Build(DateTime.Now); Assert.IsTrue(packet.IsValid || new[] { EthernetType.IpV4, EthernetType.IpV6, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(greLayer.ProtocolType), "IsValid. ProtoclType=" + greLayer.ProtocolType); GreDatagram gre = packet.Ethernet.Ip.Gre; // Remove a byte from routing Datagram newIpPayload = new Datagram(gre.Take(gre.Length - 1).ToArray()); packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsNull(packet.Ethernet.Ip.Gre.Payload); Assert.IsFalse(packet.IsValid); // SreLength is too big byte[] buffer = gre.ToArray(); buffer[buffer.Length - 1] = 200; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); // PayloadOffset is too big buffer = gre.ToArray(); buffer[gre.Length - 10] = 100; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); // PayloadOffset isn't aligned to ip buffer = gre.ToArray(); buffer[gre.Length - 10] = 3; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); // PayloadOffset isn't aligned to as buffer = gre.ToArray(); buffer[gre.Length - 16] = 1; newIpPayload = new Datagram(buffer); packetBuilder = new PacketBuilder(ethernetLayer, ipLayer, new PayloadLayer {Data = newIpPayload}); packet = packetBuilder.Build(DateTime.Now); Assert.IsFalse(packet.IsValid); } }
/// <summary> /// Handles the creation of random content for the LineDecoration. /// </summary> /// <param name="generator">The Random class that generates random numbers</param> protected override void OnRandomize(Random generator) { base.OnRandomize(generator); // _symbol is randomizable so the base method already will have randomized this class _flipAll = generator.NextBool(); _flipFirst = generator.NextBool(); _rotateWithLine = generator.NextBool(); _numSymbols = generator.Next(0, 10); _offset = generator.NextDouble() * 10; }
/// <summary> /// Returns a random UPDATE command /// </summary> public DbCommand GetUpdateCommand(Random rnd, TableMetadata table, DataStressConnection conn) { DbCommand com = CreateCommand(rnd, conn); StringBuilder cmdText = new StringBuilder(); cmdText.Append("UPDATE \""); cmdText.Append(table.TableName); cmdText.Append("\" SET "); List<TableColumn> columns = table.Columns; int numColumns = rnd.Next(2, columns.Count); bool mostlyNull = rnd.NextBool(0.1); // 10% of rows have 90% chance of each column being null, in order to test nbcrow for (int i = 0; i < numColumns; i++) { if (columns[i].ColumnName == "PrimaryKey") continue; if (columns[i].ColumnName.ToUpper() == "TIMESTAMP_FLD") continue; if (i > 1) cmdText.Append(", "); cmdText.Append(columns[i].ColumnName); cmdText.Append(" = "); if (mostlyNull && rnd.NextBool(0.9)) { cmdText.Append("NULL"); } else { DbParameter param = CreateRandomParameter(rnd, string.Format("P{0}", (i + 1)), columns[i]); cmdText.Append(param.ParameterName); com.Parameters.Add(param); } } cmdText.Append(" WHERE PrimaryKey = "); string pName = GetParameterName("P0"); cmdText.Append(pName); DbParameter keyParam = DbFactory.CreateParameter(); keyParam.ParameterName = pName; keyParam.Value = GetRandomPK(rnd, table); com.Parameters.Add(keyParam); if (ShouldModifySession(rnd)) { cmdText.Append(";").Append(GetRandomSessionModificationStatement(rnd)); } com.CommandText = cmdText.ToString(); ; return com; }
/// <summary> /// Utility function for tests /// </summary> /// <param name="rnd"></param> /// <param name="read"></param> /// <param name="poll"></param> /// <param name="handle"></param> /// <param name="xml"></param> private void TestSqlAsync(Random rnd, bool read, bool poll, bool handle, bool xml) { using (DataStressConnection conn = Factory.CreateConnection(rnd)) { if (!OpenConnection(conn)) return; DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd); SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, read, xml); bool useBeginAPI = rnd.NextBool(); IAsyncResult result = SqlCommandBeginExecute(com, read, xml, useBeginAPI); // Cancel 1/10 commands bool cancel = (rnd.Next(10) == 0); if (cancel) { if (com.Connection.State != ConnectionState.Closed) com.Cancel(); } if (result != null) WaitForAsyncOpToComplete(rnd, result, poll, handle); // At random end query or forget it if (rnd.Next(2) == 0) SqlCommandEndExecute(rnd, result, com, read, xml, cancel); // Randomly wait for the command to complete after closing the connection to verify devdiv bug 200550. // This was fixed for .NET 4.5 Task-based API, but not for the older Begin/End IAsyncResult API. conn.Close(); if (!useBeginAPI && rnd.NextBool()) result.AsyncWaitHandle.WaitOne(); } }
/// <summary> /// Returns a random INSERT command /// </summary> public DbCommand GetInsertCommand(Random rnd, TableMetadata table, DataStressConnection conn) { DbCommand com = CreateCommand(rnd, conn); StringBuilder cmdText = new StringBuilder(); cmdText.Append("INSERT INTO \""); cmdText.Append(table.TableName); cmdText.Append("\" ("); StringBuilder valuesText = new StringBuilder(); valuesText.Append(") VALUES ("); List<TableColumn> columns = table.Columns; int numColumns = rnd.Next(2, columns.Count); bool mostlyNull = rnd.NextBool(0.1); // 10% of rows have 90% chance of each column being null, in order to test nbcrow for (int i = 0; i < numColumns; i++) { if (columns[i].ColumnName.ToUpper() == "PRIMARYKEY") continue; if (i > 1) { cmdText.Append(", "); valuesText.Append(", "); } cmdText.Append(columns[i].ColumnName); if (columns[i].ColumnName.ToUpper() == "TIMESTAMP_FLD") { valuesText.Append("DEFAULT"); // Cannot insert an explicit value in a timestamp field } else if (mostlyNull && rnd.NextBool(0.9)) { valuesText.Append("NULL"); } else { DbParameter param = CreateRandomParameter(rnd, string.Format("P{0}", i + 1), columns[i]); valuesText.Append(param.ParameterName); com.Parameters.Add(param); } } // To deal databases that do not support auto-incremented columns (Oracle?) // if (!columns["PrimaryKey"].AutoIncrement) if (PrimaryKeyValueIsRequired) { DbParameter param = CreateRandomParameter(rnd, "P0", table.GetColumn("PrimaryKey")); cmdText.Append(", PrimaryKey"); valuesText.Append(", "); valuesText.Append(param.ParameterName); com.Parameters.Add(param); } valuesText.Append(")"); cmdText.Append(valuesText); if (ShouldModifySession(rnd)) { cmdText.Append(";").Append(GetRandomSessionModificationStatement(rnd)); } com.CommandText = cmdText.ToString(); return com; }
private void CheckUnion(int capacity, Random r) { BitArray b1 = BitArray.Empty, b2 = BitArray.Empty; b1.EnsureCapacity(capacity); b2.EnsureCapacity(capacity); bool[] a1 = new bool[capacity], a2 = new bool[capacity]; for (int i = 0; i < capacity; i++) { b1[i] = a1[i] = r.NextBool(); b2[i] = a2[i] = r.NextBool(); } b1.UnionWith(b2); for (int i = 0; i < capacity; i++) { a1[i] |= a2[i]; } for (int i = 0; i < capacity; i++) { Assert.Equal(a1[i], b1[i]); } }
/// <summary> /// Creates a new connection and initializes it with random connection string generated from the factory's source /// Note: if rnd is null, create a connection with minimal string required to connect to the target database /// </summary> /// <param name="rnd">Randomizes Connection Pool enablement, the application Name to randomize connection pool</param> /// <param name="options"></param> /// <returns></returns> public DataStressConnection CreateConnection(Random rnd = null, ConnectionStringOptions options = ConnectionStringOptions.Default) { // Determine connection options (connection string, identity, etc) string connectionString = CreateBaseConnectionString(rnd, options); bool clearPoolBeforeClose = false; if (rnd != null) { // Connection string and/or identity are randomized // We implement this using the Application Name field in the connection string since this field // should not affect behaviour other than connection pooling, since all connections in a pool // must have the exact same connection string (including Application Name) if (rnd.NextBool(.1)) { // Disable pooling connectionString = connectionString + ";Pooling=false;"; } else if (rnd.NextBool(0.001)) { // Use a unique Application Name to get a new connection from a new pool. We do this in order to // stress the code that creates/deletes pools. connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, GetRandomApplicationName()); // Tell DataStressConnection to call SqlConnection.ClearPool when closing the connection. This ensures // we do not keep a large number of connections in the pool that we will never use again. clearPoolBeforeClose = true; } else { switch (CurrentPoolingStressMode) { case PoolingStressMode.RandomizeConnectionStrings: // Use one of the pre-generated Application Names in order to get a pooled connection with a randomized connection string connectionString = string.Format("{0}; Pooling=true; Application Name=\"{1}\";", connectionString, _applicationNames[rnd.Next(_applicationNames.Count)]); break; default: throw DataStressErrors.UnhandledCaseError(CurrentPoolingStressMode); } } } // All options have been determined, now create DbConnection con = DbFactory.CreateConnection(); con.ConnectionString = connectionString; return new DataStressConnection(con, clearPoolBeforeClose); }
public void CheckIsTrue() { var r1 = new Random(seed); for (int capacity = 0; capacity < maxBits; capacity++) { BitVector b = BitVector.Create(capacity); for (int i = 0; i < capacity; i++) { b[i] = r1.NextBool(); } var index = 0; foreach (var word in b.Words()) { for (var i = 0; i < BitVector.BitsPerWord; i++) { if (index >= capacity) { break; } Assert.Equal(b[index], BitVector.IsTrue(word, index)); index++; } } } }
public void RandomTcpTest() { MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05"); MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5"); EthernetLayer ethernetLayer = new EthernetLayer { Source = ethernetSource, Destination = ethernetDestination }; int seed = new Random().Next(); Console.WriteLine("Seed: " + seed); Random random = new Random(seed); for (int i = 0; i != 1000; ++i) { IpV4Layer ipV4Layer = random.NextIpV4Layer(null); ipV4Layer.HeaderChecksum = null; IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Tcp, false); EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6; Layer ipLayer = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer); TcpLayer tcpLayer = random.NextTcpLayer(); PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000)); Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, tcpLayer, payloadLayer); Assert.IsTrue(packet.IsValid); // Ethernet ethernetLayer.EtherType = ethernetType; Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer"); ethernetLayer.EtherType = EthernetType.None; // Ip. if (ipLayer == ipV4Layer) { // IpV4. ipV4Layer.Protocol = IpV4Protocol.Tcp; ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum; Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer"); ipV4Layer.HeaderChecksum = null; } else { Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IPv6 Layer"); } // TCP tcpLayer.Checksum = packet.Ethernet.Ip.Tcp.Checksum; Assert.AreEqual(tcpLayer, packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer"); Assert.AreNotEqual(random.NextTcpLayer(), packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer"); Assert.AreEqual(tcpLayer.GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer"); Assert.AreNotEqual(random.NextTcpLayer().GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer"); Assert.AreEqual((uint)(packet.Ethernet.Ip.Tcp.SequenceNumber + packet.Ethernet.Ip.Tcp.PayloadLength), packet.Ethernet.Ip.Tcp.NextSequenceNumber); foreach (TcpOption option in packet.Ethernet.Ip.Tcp.Options.OptionsCollection) { Assert.AreEqual(option, option); Assert.AreEqual(option.GetHashCode(), option.GetHashCode()); Assert.IsFalse(string.IsNullOrEmpty(option.ToString())); Assert.IsFalse(option.Equals(null)); Assert.IsFalse(option.Equals(2)); } Assert.AreEqual(tcpLayer.Options, packet.Ethernet.Ip.Tcp.Options, "Options"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Acknowledgment) == TcpControlBits.Acknowledgment, packet.Ethernet.Ip.Tcp.IsAcknowledgment, "IsAcknowledgment"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.CongestionWindowReduced) == TcpControlBits.CongestionWindowReduced, packet.Ethernet.Ip.Tcp.IsCongestionWindowReduced, "IsCongestionWindowReduced"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.ExplicitCongestionNotificationEcho) == TcpControlBits.ExplicitCongestionNotificationEcho, packet.Ethernet.Ip.Tcp.IsExplicitCongestionNotificationEcho, "IsExplicitCongestionNotificationEcho"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Fin) == TcpControlBits.Fin, packet.Ethernet.Ip.Tcp.IsFin, "IsFin"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Push) == TcpControlBits.Push, packet.Ethernet.Ip.Tcp.IsPush, "IsPush"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Reset) == TcpControlBits.Reset, packet.Ethernet.Ip.Tcp.IsReset, "IsReset"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Synchronize) == TcpControlBits.Synchronize, packet.Ethernet.Ip.Tcp.IsSynchronize, "IsSynchronize"); Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Urgent) == TcpControlBits.Urgent, packet.Ethernet.Ip.Tcp.IsUrgent, "IsUrgent"); Assert.AreEqual(0, packet.Ethernet.Ip.Tcp.Reserved); Assert.IsFalse(packet.Ethernet.Ip.Tcp.IsChecksumOptional, "IsChecksumOptional"); Assert.AreEqual(TcpDatagram.HeaderMinimumLength + tcpLayer.Options.BytesLength + payloadLayer.Length, packet.Ethernet.Ip.Tcp.Length, "Total Length"); Assert.IsTrue(packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect"); Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Tcp.Payload, "Payload"); } }
private static void CreateRandomIpV4Payload(Random random, IpV4Layer ipV4Layer, List<ILayer> layers) { if (random.NextBool(20)) { // Finish with payload. PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100)); layers.Add(payloadLayer); return; } ipV4Layer.Protocol = null; if (random.NextBool()) ipV4Layer.Fragmentation = IpV4Fragmentation.None; switch (random.Next(0, 9)) { case 0: // IpV4. case 1: IpV4Layer innerIpV4Layer = random.NextIpV4Layer(); layers.Add(innerIpV4Layer); CreateRandomIpV4Payload(random, innerIpV4Layer, layers); return; case 2: // Igmp. layers.Add(random.NextIgmpLayer()); return; case 3: // Icmp. IcmpLayer icmpLayer = random.NextIcmpLayer(); layers.Add(icmpLayer); layers.AddRange(random.NextIcmpPayloadLayers(icmpLayer)); return; case 4: // Gre. GreLayer greLayer = random.NextGreLayer(); layers.Add(greLayer); CreateRandomEthernetPayload(random, greLayer, layers); return; case 5: // Udp. case 6: UdpLayer udpLayer = random.NextUdpLayer(); layers.Add(udpLayer); CreateRandomUdpPayload(random, udpLayer, layers); return; case 7: // Tcp. case 8: TcpLayer tcpLayer = random.NextTcpLayer(); layers.Add(tcpLayer); CreateRandomTcpPayload(random, tcpLayer, layers); return; default: throw new InvalidOperationException("Invalid value."); } }
private void CheckUnionCore(int capacity1, int capacity2, Random r) { BitVector b1 = BitVector.Empty, b2 = BitVector.Empty; b1.EnsureCapacity(capacity1); b2.EnsureCapacity(capacity2); var maxCapacity = Math.Max(capacity1, capacity2); bool[] a1 = new bool[maxCapacity], a2 = new bool[maxCapacity]; for (int i = 0; i < capacity1; i++) { b1[i] = a1[i] = r.NextBool(); } for (int i = 0; i < capacity2; i++) { b2[i] = a2[i] = r.NextBool(); } bool changed = b1.UnionWith(b2); bool changed2 = false; for (int i = 0; i < maxCapacity; i++) { bool a = a1[i]; a1[i] |= a2[i]; changed2 |= (a != a1[i]); } for (int i = 0; i < maxCapacity; i++) { Assert.Equal(a1[i], b1[i]); } Assert.Equal(changed2, changed); }
private static void CreateRandomIpPayload(Random random, Layer ipLayer, List<ILayer> layers) { IpV6Layer ipV6Layer = ipLayer as IpV6Layer; if (ipV6Layer != null) { var headers = ipV6Layer.ExtensionHeaders.Headers; if (headers.Any() && headers.Last().Protocol == IpV4Protocol.EncapsulatingSecurityPayload) return; } if (ipV6Layer != null ? ipV6Layer.LastNextHeader != null : random.NextBool(20)) { // Finish with payload. PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100)); layers.Add(payloadLayer); return; } IpV4Layer ipV4Layer = ipLayer as IpV4Layer; if (ipV4Layer != null) { ipV4Layer.Protocol = null; if (random.NextBool()) ipV4Layer.Fragmentation = IpV4Fragmentation.None; } switch (random.Next(0, 11)) { case 0: // IpV4. case 1: IpV4Layer innerIpV4Layer = random.NextIpV4Layer(); layers.Add(innerIpV4Layer); CreateRandomIpPayload(random, innerIpV4Layer, layers); return; case 2: // IpV6. case 3: IpV6Layer innerIpV6Layer = random.NextIpV6Layer(random.NextBool(20)); layers.Add(innerIpV6Layer); CreateRandomIpPayload(random, innerIpV6Layer, layers); return; case 4: // Igmp. layers.Add(random.NextIgmpLayer()); return; case 5: // Icmp. IcmpLayer icmpLayer = random.NextIcmpLayer(); layers.Add(icmpLayer); layers.AddRange(random.NextIcmpPayloadLayers(icmpLayer)); return; case 6: // Gre. GreLayer greLayer = random.NextGreLayer(); layers.Add(greLayer); CreateRandomEthernetPayload(random, greLayer, layers); return; case 7: // Udp. case 8: UdpLayer udpLayer = random.NextUdpLayer(); layers.Add(udpLayer); CreateRandomUdpPayload(random, udpLayer, layers); return; case 9: // Tcp. case 10: TcpLayer tcpLayer = random.NextTcpLayer(); layers.Add(tcpLayer); CreateRandomTcpPayload(random, tcpLayer, layers); return; default: throw new InvalidOperationException("Invalid value."); } }
private void CheckTrueBitsCore(int capacity, Random r1, Random r2) { BitVector b = BitVector.Create(capacity); for (int i = 0; i < capacity; i++) { b[i] = r1.NextBool(); } IEnumerable<int> i1 = b.TrueBits(); IEnumerator<int> i2 = i1.GetEnumerator(); for (int i = 0; i < capacity; i++) { if (r2.NextBool()) { Assert.True(i2.MoveNext()); Assert.Equal(i2.Current, i); } } Assert.False(i2.MoveNext()); i2.Dispose(); }
public override string CreateBaseConnectionString(Random rnd, ConnectionStringOptions options) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); switch (_scenario) { case SqlClientScenario.Sql: builder.DataSource = _source.DataSource; builder.InitialCatalog = _source.Database; break; default: throw new InvalidOperationException("missing case for " + _scenario); } // Randomize between Windows Authentication and SQL Authentication // Note that having 2 options here doubles the number of connection pools bool integratedSecurity = false; if (_source.SupportsWindowsAuthentication) { if (string.IsNullOrEmpty(_source.User)) // if sql login is not provided integratedSecurity = true; else integratedSecurity = (rnd != null) ? (rnd.Next(2) == 0) : true; } if (integratedSecurity) { builder.IntegratedSecurity = true; } else { builder.UserID = _source.User; builder.Password = _source.Password; } if (CurrentPoolingStressMode == PoolingStressMode.RandomizeConnectionStrings && rnd != null) { // Randomize connection string // Randomize packetsize // Note that having 2 options here doubles the number of connection pools if (rnd.NextBool()) { builder.PacketSize = 8192; } else { builder.PacketSize = 512; } // If test case allows randomization and doesn't disallow MultiSubnetFailover, then enable MultiSubnetFailover 20% of the time // Note that having 2 options here doubles the number of connection pools if (!_source.DisableMultiSubnetFailoverSetup && !options.HasFlag(ConnectionStringOptions.DisableMultiSubnetFailover) && rnd != null && rnd.Next(5) == 0) { string msfHostName; if (integratedSecurity) { msfHostName = _multiSubnetSetupHelper.MultiSubnetFailoverHostNameForIntegratedSecurity; } else { msfHostName = _multiSubnetSetupHelper.GetMultiSubnetFailoverHostName(rnd); } string serverName; // replace with build which has host name with multiple IP addresses builder = NetUtils.GetMultiSubnetFailoverConnectionString(builder.ConnectionString, msfHostName, out serverName); } // Randomize between using Named Pipes and TCP providers // Note that having 2 options here doubles the number of connection pools if (rnd != null) { if (rnd.Next(2) == 0) { builder.DataSource = "tcp:" + builder.DataSource; } else if (!_source.DisableNamedPipes) { // Named Pipes if (builder.DataSource.Equals("(local)")) builder.DataSource = "np:" + builder.DataSource; else builder.DataSource = @"np:\\" + builder.DataSource.Split(',')[0] + @"\pipe\sql\query"; } } // Set MARS if it is requested by the test case if (options.HasFlag(ConnectionStringOptions.EnableMars)) { builder.MultipleActiveResultSets = true; } // Disable connection resiliency, which is on by default, 20% of the time. if (rnd != null && rnd.NextBool(.2)) { builder.ConnectRetryCount = 0; } } else { // Minimal randomization of connection string // Enable MARS for all scenarios builder.MultipleActiveResultSets = true; } builder.MaxPoolSize = 1000; return builder.ToString(); }
private static void CreateRandomEthernetPayload(Random random, EthernetBaseLayer ethernetBaseLayer, List<ILayer> layers) { if (random.NextBool(20)) { // Finish with payload. PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100)); layers.Add(payloadLayer); return; } ethernetBaseLayer.EtherType = EthernetType.None; switch (random.NextInt(0, 7)) { case 0: // VLanTaggedFrame. case 1: VLanTaggedFrameLayer vLanTaggedFrameLayer = random.NextVLanTaggedFrameLayer(); layers.Add(vLanTaggedFrameLayer); CreateRandomEthernetPayload(random, vLanTaggedFrameLayer, layers); return; case 2: // ARP. EthernetLayer ethernetLayer = (ethernetBaseLayer as EthernetLayer); if (ethernetLayer != null) ethernetLayer.Destination = MacAddress.Zero; layers.Add(random.NextArpLayer()); return; case 3: // IPv4. case 4: IpV4Layer ipV4Layer = random.NextIpV4Layer(); layers.Add(ipV4Layer); CreateRandomIpPayload(random, ipV4Layer, layers); return; case 5: // IPv6 case 6: IpV6Layer ipV6Layer = random.NextIpV6Layer(random.NextBool(20)); layers.Add(ipV6Layer); CreateRandomIpPayload(random, ipV6Layer, layers); return; default: throw new InvalidOperationException("Invalid value."); } }
// This function is tasked with spawning items relative to already placed item // will return a list of spawned items so that SpawnItemsInRoom know what's left to spawn public static int SpawnRelatives(Spawnable spawned, Vector2 spawnedPos, Quaternion spawnedRot, Random rand, ref HashSet <GameObject> spawnedObjects, ref List <RoomType.SpawnListItem> availableItems, int min, int max, int currentRecusion = 0) { int spawnedOfSameCount = 0; if (currentRecusion < 2) { int spawnedIndex = availableItems.FindIndex(spawnableItem => spawnableItem.Spawnable == spawned); for (int i = 0; i < spawned.relativeSpawnList.Length; i++) { int relationIndex = availableItems.FindIndex(spawnableItem => spawnableItem.Spawnable == spawned.relativeSpawnList[i].Spawnable); if (relationIndex != -1 && spawnedIndex <= relationIndex) { int spawnCount = rand.NextInclusive(min, max); int spawnedObjectsCount = 0; // if the rotation is set (not random) if (spawned.relativeSpawnList[i].AngleIteration != 0) { for (int j = 0; j < spawnCount && Math.Abs(j * spawned.relativeSpawnList[i].AngleIteration) < 360; j++) { Quaternion objectQuaternion = Quaternion.Euler(0, j * spawned.relativeSpawnList[i].AngleIteration + spawnedRot.eulerAngles.y, 0); Vector3 spawnPosition = new Vector3(spawnedPos.x, 0, spawnedPos.y); Vector3 forward = objectQuaternion * new Vector3(0, 0, 1); if (TryResolvePositionPhysically(spawned.relativeSpawnList[i].Spawnable, ref spawnPosition, -forward, objectQuaternion)) { spawnedObjects.Add(GameObject.Instantiate(spawned.relativeSpawnList[i].Spawnable.gameObject, spawnPosition, objectQuaternion)); SpawnRelatives(spawned.relativeSpawnList[i].Spawnable, new Vector2Int((int)spawnPosition.x, (int)spawnPosition.z), objectQuaternion, rand, ref spawnedObjects, ref availableItems, min, max, ++currentRecusion); } spawnedObjectsCount = j; } int newMin = ((min - spawnedObjectsCount) > 0) ? min - spawnedObjectsCount : 0; int newMax = ((max - spawnedObjectsCount) > 0) ? max - spawnedObjectsCount : 0; RoomType.SpawnListItem updatedItem = new RoomType.SpawnListItem(availableItems[relationIndex].AngleIteration, new Vector2Int(newMin, newMax), availableItems[relationIndex].Spawnable); availableItems[relationIndex] = updatedItem; if (spawnedIndex == relationIndex) { spawnedOfSameCount++; } } else { for (int j = 0; j < spawnCount; j++) { Quaternion objectQuaternion = Quaternion.Euler(0, rand.NextInclusive(0, availableItems[relationIndex].Spawnable.angleMaxOffset), 0); float xPos = spawnedPos.x + (rand.NextFloat() * (spawned.neededSpawnSpace.extents.x * 0.75f)) * (rand.NextBool() ? -1 : 1); float zPos = spawnedPos.y + (rand.NextFloat() * (spawned.neededSpawnSpace.extents.z * 0.75f)) * (rand.NextBool() ? -1 : 1); Vector3 spawnPosition = new Vector3(xPos, 0, zPos); if (TryResolvePositionPhysically(spawned.relativeSpawnList[i].Spawnable, ref spawnPosition, null, objectQuaternion)) { spawnedObjects.Add(GameObject.Instantiate(spawned.relativeSpawnList[i].Spawnable.gameObject, spawnPosition, objectQuaternion)); SpawnRelatives(spawned.relativeSpawnList[i].Spawnable, new Vector2Int((int)spawnPosition.x, (int)spawnPosition.z), objectQuaternion, rand, ref spawnedObjects, ref availableItems, min, max, ++currentRecusion); } spawnedObjectsCount = j; } int newMin = ((min - spawnedObjectsCount) > 0) ? min - spawnedObjectsCount : 0; int newMax = ((max - spawnedObjectsCount) > 0) ? max - spawnedObjectsCount : 0; RoomType.SpawnListItem updatedItem = new RoomType.SpawnListItem(availableItems[relationIndex].AngleIteration, new Vector2Int(newMin, newMax), availableItems[relationIndex].Spawnable); availableItems[relationIndex] = updatedItem; if (spawnedIndex == relationIndex) { spawnedOfSameCount++; } } } } } return(spawnedOfSameCount); }