Exemple #1
0
        private async Task TestFeedEvaluationSourceTask(ConcurrentStack<SourceModel> sources, Logger logger)
        {
            var assertHelper = new AssertHelper();

            SourceModel source;
            while (sources.TryPop(out source))
            {
                var sourceLogEntry = new LogEntry()
                {
                    Content = "Testing " + source.Name
                };

                var feeds = new ConcurrentStack<FeedModel>(source.Feeds);
                var tasks = new List<Task>();
                for (int i = 0; i < _maxThreads; i++)
                {
                    tasks.Add(TestFeedEvaluationFeedTask(feeds, source, sourceLogEntry, assertHelper));
                }

                await Task.WhenAll(tasks);
                assertHelper.NotAlwaysDefinedPropertiesCheckOut(source.Source);

                logger.AddLog(sourceLogEntry);
            }
        }
Exemple #2
0
 public void ConstructorParameter()
 {
     AssertHelper.ExpectedException <ArgumentNullException>(() => new GenericMockViewModel(null));
 }
Exemple #3
0
 public void Test_Validate_2()
 {
     AssertHelper.Throws <ArgumentNullException>(() => _builder.Where("", "a"));
 }
Exemple #4
0
 public void testGetAbsEmptyHumanishName()
 {
     AssertHelper.Throws <InvalidOperationException>(() => new URIish().getHumanishName(), "empty path is useless");
 }
Exemple #5
0
 public void Test_GetValue_Validate()
 {
     AssertHelper.Throws <ArgumentNullException>(() => Enum.GetValue <EnumSample>(null), "member");
     AssertHelper.Throws <ArgumentNullException>(() => Enum.GetValue <EnumSample>(string.Empty), "member");
     AssertHelper.Throws <ArgumentNullException>(() => Enum.GetValue <Sample>(string.Empty), "member");
 }
Exemple #6
0
        public async Task CrudAsync()
        {
            // Prepare initial record.
            var record = TestDataFactory.GetFullyFilledOutRecord(_appIdWithRecords, default);

            // Insert
            var insertResponse = await _apiClient.SaveRecordAsync(record);       // Used for single delete

            var secondInsertResponse = await _apiClient.SaveRecordAsync(record); // Used for batch delete

            AssertHelper.AssertSuccess(insertResponse);

            // Update
            record.RecordId = insertResponse.Value.Id;
            UpdateRecordFields(record);

            var updateResponse = await _apiClient.SaveRecordAsync(record);

            AssertHelper.AssertSuccess(updateResponse);

            // Reads
            // Get by ID
            var getRequest = new GetRecordRequest(_appIdWithRecords, insertResponse.Value.Id)
            {
                FieldIds = { _fieldId },
            };
            var getResponse = await _apiClient.GetRecordAsync(getRequest);

            AssertHelper.AssertSuccess(getResponse);
            AssertHelper.AssertCasting(getResponse.Value);

            // Get batch
            var getBatchRequest = new GetRecordsRequest
            {
                AppId     = _appIdWithRecords,
                RecordIds = { insertResponse.Value.Id, secondInsertResponse.Value.Id },
                FieldIds  = { _fieldId },
            };
            var batchGetResponse = await _apiClient.GetRecordsAsync(getBatchRequest);

            AssertHelper.AssertSuccess(batchGetResponse);
            AssertHelper.AssertCasting(batchGetResponse.Value.Items);

            // Get by app
            var pagingRequest   = new PagingRequest(1, 10);
            var getByAppRequest = new GetRecordsByAppRequest(_appIdWithRecords, pagingRequest)
            {
                FieldIds = { _fieldId },
            };
            var getByAppResponse = await _apiClient.GetRecordsForAppAsync(getByAppRequest);

            AssertHelper.AssertSuccess(getByAppResponse);
            AssertHelper.AssertCasting(getByAppResponse.Value.Items);

            // Query
            var queryRequest = new QueryRecordsRequest
            {
                AppId = _appIdWithRecords,
            };
            var queryResponse = await _apiClient.QueryRecordsAsync(queryRequest);

            AssertHelper.AssertSuccess(queryResponse);
            AssertHelper.AssertCasting(queryResponse.Value.Items);

            // Delete
            // Single delete
            var deleteResponse = await _apiClient.DeleteRecordAsync(_appIdWithRecords, insertResponse.Value.Id);

            AssertHelper.AssertSuccess(deleteResponse);

            // Batch delete
            var batchDeleteRequest  = new DeleteRecordsRequest(_appIdWithRecords, new[] { secondInsertResponse.Value.Id });
            var batchDeleteResponse = await _apiClient.DeleteRecordsAsync(batchDeleteRequest);

            AssertHelper.AssertSuccess(batchDeleteResponse);
        }
Exemple #7
0
 public void TestRegister_Null()
 {
     AssertHelper.Throws <ArgumentNullException>(() => _manager.Register(null));
 }
 public void WhenQueryingDirect_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <Bar>(x => x.NonVirtualValue == "bar"));
 }
 public void WhenQueryingField_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <Bar>(x => x.FieldValue == "bar"));
 }
Exemple #10
0
 public void WhenOperatorIsLessThanOrEqual_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <IFoo>(x => x.Count <= 5));
 }
Exemple #11
0
 public void WhenCombiningWithOrRatherThanLogicalAnd_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <IFoo>(x => x.Count == 5 || x.Value == "foo"));
 }
Exemple #12
0
 public void WhenOperatorIsGreaterThan_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <IFoo>(x => x.Count > 5));
 }
Exemple #13
0
 public void WhenOperatorIsNotEqual_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <IFoo>(x => x.Value != "foo"));
 }
Exemple #14
0
 public void WhenQueryingLastOrDefault_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mocks.Of <IFoo>().LastOrDefault());
 }
Exemple #15
0
 public void WhenQueryingAny_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mocks.Of <IFoo>().Any());
 }
Exemple #16
0
 public void WhenQueryingOnFluent_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <Foo>(x => x.VirtualBar.FieldValue == "bar"));
 }
        protected override void AnalyzeAssertInvocation(OperationAnalysisContext context, IInvocationOperation assertOperation)
        {
            if (!AssertHelper.TryGetActualAndConstraintOperations(assertOperation,
                                                                  out var actualOperation, out var constraintExpression))
            {
                return;
            }

            if (actualOperation is null)
            {
                return;
            }

            var actualType = AssertHelper.GetUnwrappedActualType(actualOperation);

            if (actualType is null)
            {
                return;
            }

            foreach (var constraintPartExpression in constraintExpression.ConstraintParts)
            {
                if (constraintPartExpression.HasIncompatiblePrefixes() ||
                    HasCustomComparer(constraintPartExpression) ||
                    constraintPartExpression.HasUnknownExpressions())
                {
                    continue;
                }

                var constraintMethod = constraintPartExpression.GetConstraintMethod();
                if (constraintMethod is null)
                {
                    continue;
                }

                if (!SupportedConstraints.Contains(constraintMethod.Name))
                {
                    continue;
                }

                var expectedOperation = constraintPartExpression.GetExpectedArgument();
                if (expectedOperation is null)
                {
                    continue;
                }

                var expectedType = expectedOperation.Type;
                if (expectedType is null)
                {
                    continue;
                }

                if (actualType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
                {
                    actualType = ((INamedTypeSymbol)actualType).TypeArguments[0];
                }

                if (expectedType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
                {
                    expectedType = ((INamedTypeSymbol)expectedType).TypeArguments[0];
                }

                if (actualType.SpecialType == SpecialType.System_Object ||
                    expectedType.SpecialType == SpecialType.System_Object)
                {
                    // An instance of object might not implement IComparable resulting in runtime errors.
                    context.ReportDiagnostic(Diagnostic.Create(
                                                 comparableOnObjectDescriptor,
                                                 expectedOperation.Syntax.GetLocation(),
                                                 constraintMethod.Name));
                }
                else if (!CanCompare(actualType, expectedType, context.Compilation))
                {
                    context.ReportDiagnostic(Diagnostic.Create(
                                                 comparableTypesDescriptor,
                                                 expectedOperation.Syntax.GetLocation(),
                                                 constraintMethod.Name));
                }
            }
        }
Exemple #18
0
 public void WhenIntermediateFluentReadonly_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mock.Of <Foo>(x => x.Bar.VirtualValue == "bar"));
 }
Exemple #19
0
        private unsafe TestResult ExecuteMethod(ExecutionContext context)
        {
            byte *returnBox = stackalloc byte[MaxReturnBoxSize];

            Setup();
            var methodInfo = _originalMethod.Method.MethodInfo;

            if (!RunningArmTestOnIntelCPU(methodInfo))
            {
                var arguments = GetArgumentsArray(_originalMethod);

                // Special case for Compiler Exceptions when IL can't be translated
                if (_expectCompilerException)
                {
                    // We still need to transform arguments here in case there's a function pointer that we expect to fail compilation.
                    var expectedExceptionResult = TryExpectedException(
                        context,
                        () => TransformArguments(_originalMethod.Method.MethodInfo, arguments, out _, out _, returnBox, out _),
                        "Transforming arguments",
                        type => true,
                        "Any exception",
                        false,
                        false);
                    if (expectedExceptionResult != TryExpectedExceptionResult.DidNotThrowException)
                    {
                        return(context.CurrentResult);
                    }

                    return(HandleCompilerException(context, methodInfo));
                }

                object[] nativeArgs;
                Type[]   nativeArgTypes;
                TransformArguments(_originalMethod.Method.MethodInfo, arguments, out nativeArgs, out nativeArgTypes, returnBox, out Type returnBoxType);

                bool isInRegistry = false;
                Func <object, object[], object> nativeDelegateCaller;
                var delegateType = CreateNativeDelegateType(_originalMethod.Method.MethodInfo.ReturnType, nativeArgTypes, out isInRegistry, out nativeDelegateCaller);
                if (!isInRegistry)
                {
                    Console.WriteLine($"Warning, the delegate for the method `{_originalMethod.Method}` has not been generated");
                }

                Delegate compiledFunction;
                try
                {
                    compiledFunction = CompileDelegate(context, methodInfo, delegateType, returnBox, out _);
                }
                catch (Exception ex) when(_expectedException != null && ex.GetType() == _expectedException)
                {
                    context.CurrentResult.SetResult(ResultState.Success);
                    return(context.CurrentResult);
                }

                Assert.IsTrue(returnBoxType == null || Marshal.SizeOf(returnBoxType) <= MaxReturnBoxSize);

                if (compiledFunction == null)
                {
                    return(context.CurrentResult);
                }

                if (_compileOnly) // If the test only wants to compile the code, bail now.
                {
                    return(context.CurrentResult);
                }
                else if (_expectedException != null) // Special case if we have an expected exception
                {
                    if (TryExpectedException(context, () => _originalMethod.Method.Invoke(context.TestObject, arguments), ".NET", type => type == _expectedException, _expectedException.FullName, false) != TryExpectedExceptionResult.ThrewExpectedException)
                    {
                        return(context.CurrentResult);
                    }

                    if (TryExpectedException(context, () => nativeDelegateCaller(compiledFunction, nativeArgs), "Native", type => type == _expectedException, _expectedException.FullName, true) != TryExpectedExceptionResult.ThrewExpectedException)
                    {
                        return(context.CurrentResult);
                    }
                }
                else
                {
                    object resultNative = null;

                    // We are forced to run native before managed, because on IL2CPP, if a parameter
                    // is a ref, it will keep the same memory location for both managed and burst
                    // while in .NET CLR we have a different behavior
                    // The result is that on functions expecting the same input value through the ref
                    // it won't be anymore true because the managed could have modified the value before
                    // burst

                    // ------------------------------------------------------------------
                    // Run Native (Before)
                    // ------------------------------------------------------------------
                    if (!RunManagedBeforeNative)
                    {
                        resultNative = nativeDelegateCaller(compiledFunction, nativeArgs);
                        if (returnBoxType != null)
                        {
                            resultNative = Marshal.PtrToStructure((IntPtr)returnBox, returnBoxType);
                        }
                    }

                    // ------------------------------------------------------------------
                    // Run Managed
                    // ------------------------------------------------------------------
                    object resultClr;
                    // This option skips running the managed version completely
                    var overrideManagedResult = _originalMethod.Properties.Get("OverrideManagedResult");
                    if (overrideManagedResult != null)
                    {
                        Console.WriteLine($"Using OverrideManagedResult: `{overrideManagedResult}` to compare to burst `{resultNative}`, managed version not run");
                        resultClr = overrideManagedResult;
                    }
                    else
                    {
                        resultClr = _originalMethod.Method.Invoke(context.TestObject, arguments);

                        if (returnBoxType != null)
                        {
                            resultClr = Marshal.PtrToStructure((IntPtr)returnBox, returnBoxType);
                        }
                    }

                    var overrideResultOnMono = _originalMethod.Properties.Get("OverrideResultOnMono");
                    if (overrideResultOnMono != null)
                    {
                        Console.WriteLine($"Using OverrideResultOnMono: `{overrideResultOnMono}` instead of `{resultClr}` compare to burst `{resultNative}`");
                        resultClr = overrideResultOnMono;
                    }

                    // ------------------------------------------------------------------
                    // Run Native (After)
                    // ------------------------------------------------------------------
                    if (RunManagedBeforeNative)
                    {
                        resultNative = nativeDelegateCaller(compiledFunction, nativeArgs);
                        if (returnBoxType != null)
                        {
                            resultNative = Marshal.PtrToStructure((IntPtr)returnBox, returnBoxType);
                        }
                    }

                    // Use our own version (for handling correctly float precision)
                    AssertHelper.AreEqual(resultClr, resultNative, GetULP());

                    // Validate deterministic outputs - Disabled for now
                    //RunDeterminismValidation(_originalMethod, resultNative);

                    // Allow to process native result
                    ProcessNativeResult(_originalMethod, resultNative);

                    context.CurrentResult.SetResult(ResultState.Success);

                    PostAssert(context);
                }

                // Check that the method is actually in the registry
                Assert.True(isInRegistry, "The test method is not in the registry, recompile the project with the updated StaticDelegateRegistry.generated.cs");

                // Make an attempt to clean up arguments (to reduce wasted native heap memory)
                DisposeObjects(arguments);
                DisposeObjects(nativeArgs);
            }

            // Compile the method once again, this time for Arm CPU to check against gold asm images
            CompileDelegateForArm(methodInfo);

            CompleteTest(context);

            return(context.CurrentResult);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Pokedex.Pokedex  pokedex = AppStateHelper.Pokedex(Application);
            PokemonPartyBase pkmn    = null;

            if (Request.QueryString.Count == 0 || Request.QueryString.Count > 2)
            {
                throw new WebException(400);
            }
            if (Request.QueryString["offer"] != null ||
                Request.QueryString["exchange"] != null)
            {
                String generation = Request.QueryString["g"];
                if (generation == null ||
                    Request.QueryString.Count != 2)
                {
                    throw new WebException(400);
                }

                int  tradeId;
                bool isExchanged;

                if (Request.QueryString["offer"] != null)
                {
                    tradeId     = Convert.ToInt32(Request.QueryString["offer"]);
                    isExchanged = false;
                }
                else if (Request.QueryString["exchange"] != null)
                {
                    tradeId     = Convert.ToInt32(Request.QueryString["exchange"]);
                    isExchanged = true;
                }
                else
                {
                    AssertHelper.Unreachable();
                    throw new WebException(400);
                }

                // todo: when userprofiles are ready, add checks that they allow viewing their GTS history
                switch (generation)
                {
                case "4":
                {
                    GtsRecord4 record = Database.Instance.GtsGetRecord4(pokedex, tradeId, isExchanged, true);
                    if (record != null)
                    {
                        pkmn = new PokemonParty4(pokedex, record.Data.ToArray());
                    }
                } break;

                case "5":
                {
                    GtsRecord5 record = Database.Instance.GtsGetRecord5(pokedex, tradeId, isExchanged, true);
                    if (record != null)
                    {
                        pkmn = new PokemonParty5(pokedex, record.Data.ToArray());
                    }
                } break;

                default:
                    throw new WebException(400);
                }
            }
            else if (Request.QueryString["check"] != null)
            {
                int checkId = Convert.ToInt32(Request.QueryString["check"]);
                throw new NotImplementedException();
            }
            else
            {
                throw new WebException(400);
            }

            if (pkmn == null)
            {
                throw new WebException(403);
            }

            Bind(pkmn);
        }
Exemple #21
0
 public void testGetNullHumanishName()
 {
     AssertHelper.Throws <InvalidOperationException>(() => new URIish().getHumanishName(), "path must be not null");
 }
        public override void ProcessGamestatsRequest(byte[] request, MemoryStream response, string url, int pid, HttpContext context, GamestatsSession session)
        {
            Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(context.Application);

            switch (url)
            {
            default:
                SessionManager.Remove(session);

                // unrecognized page url
                ShowError(context, 404);
                return;

                #region Common
            // Called during startup. Seems to contain trainer profile stats.
            case "/syachi2ds/web/common/setProfile.asp":
                SessionManager.Remove(session);

                if (request.Length != 100)
                {
                    ShowError(context, 400);
                    return;
                }

#if !DEBUG
                try
                {
#endif
                // this blob appears to share the same format with GenIV only with (obviously) a GenV string for the trainer name
                // and the email-related fields dummied out.
                // Specifically, email, notification status, and the two secrets appear to always be 0.
                byte[] profileBinary = new byte[100];
                Array.Copy(request, 0, profileBinary, 0, 100);
                TrainerProfile5 profile = new TrainerProfile5(pid, profileBinary);
                Database.Instance.GamestatsSetProfile5(profile);
#if !DEBUG
            }
            catch { }
#endif

                response.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                               0, 8);
                break;
                #endregion

                #region GTS
            // Called during startup. Unknown purpose.
            case "/syachi2ds/web/worldexchange/info.asp":
                SessionManager.Remove(session);

                // todo: find out the meaning of this request.
                // is it simply done to check whether the GTS is online?
                response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
                break;

            // Called during startup and when you check your pokemon's status.
            case "/syachi2ds/web/worldexchange/result.asp":
            {
                SessionManager.Remove(session);

                // todo: more fun stuff is contained in this blob on genV.
                // my guess is that it's trainer profile info like setProfile.asp
                // There's a long string of 0s which could be a trainer card signature raster

                GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid);

                if (record == null)
                {
                    // No pokemon in the system
                    response.Write(new byte[] { 0x05, 0x00 }, 0, 2);
                }
                else if (record.IsExchanged > 0)
                {
                    // traded pokemon arriving!!!
                    response.Write(record.Save(), 0, 296);
                }
                else
                {
                    // my existing pokemon is in the system, untraded
                    response.Write(new byte[] { 0x04, 0x00 }, 0, 2);
                }
            } break;

            // Called after result.asp returns 4 when you check your pokemon's status
            case "/syachi2ds/web/worldexchange/get.asp":
            {
                SessionManager.Remove(session);

                // this is only called if result.asp returned 4.
                // todo: what does this do if the contained pokemon is traded??
                // todo: the same big blob of stuff from result.asp is sent here too.

                GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid);

                if (record == null)
                {
                    // No pokemon in the system
                    // what do here?
                    // todo: we should probably repeat the previous record
                    // that was in here before delete.asp was called.
                    // That is... if we still had it. -__-;
                    ShowError(context, 400);
                    return;
                }
                else
                {
                    // just write the record whether traded or not...
                    response.Write(record.Save(), 0, 296);
                }
            } break;

            // Called after result.asp returns an inbound pokemon record to delete it
            case "/syachi2ds/web/worldexchange/delete.asp":
            {
                SessionManager.Remove(session);

                // todo: the same big blob of stuff from result.asp is sent here too.

                GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid);
                if (record == null)
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                }
                else if (record.IsExchanged > 0)
                {
                    // delete the arrived pokemon from the system
                    // todo: add transactions
                    // todo: log the successful trade?
                    // (either here or when the trade is done)
                    bool success = Database.Instance.GtsDeletePokemon5(pid);
                    if (success)
                    {
                        response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
                    }
                    else
                    {
                        response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                    }
                }
                else
                {
                    // own pokemon is there, fail. Use return.asp instead.
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                }
            } break;

            // called to delete your own pokemon after taking it back
            case "/syachi2ds/web/worldexchange/return.asp":
            {
                SessionManager.Remove(session);

                GtsRecord5 record = Database.Instance.GtsDataForUser5(pokedex, pid);
                if (record == null)
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                }
                else if (record.IsExchanged > 0)
                {
                    // a traded pokemon is there, fail. Use delete.asp instead.
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                }
                else
                {
                    // delete own pokemon
                    // todo: add transactions
                    bool success = Database.Instance.GtsDeletePokemon5(pid);
                    if (success)
                    {
                        response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
                        // todo: invalidate cache
                        //manager.RefreshStats();
                    }
                    else
                    {
                        response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                    }
                }
            } break;

            // Called when you deposit a pokemon into the system.
            case "/syachi2ds/web/worldexchange/post.asp":
            {
                if (request.Length != 432)
                {
                    SessionManager.Remove(session);
                    ShowError(context, 400);
                    return;
                }

                // todo: add transaction
                if (Database.Instance.GtsDataForUser5(pokedex, pid) != null)
                {
                    // there's already a pokemon inside
                    // Force the player out so they'll recheck its status.
                    SessionManager.Remove(session);
                    response.Write(new byte[] { 0x0e, 0x00 }, 0, 2);
                    break;
                }

                // keep the record in memory while we wait for post_finish.asp request
                byte[] recordBinary = new byte[296];
                Array.Copy(request, 0, recordBinary, 0, 296);
                GtsRecord5 record = new GtsRecord5(pokedex, recordBinary);
                record.IsExchanged = 0;

                // todo: figure out what bytes 296-431 do:
                // appears to be 4 bytes of 00, 128 bytes of stuff, 4 bytes of 80 00 00 00
                // probably a pkvldtprod signature

                if (!record.Validate())
                {
                    // hack check failed
                    SessionManager.Remove(session);

                    // responses:
                    // 0x00: bsod
                    // 0x01: successful deposit
                    // 0x02: Communication error 13265
                    // 0x03: Communication error 13264
                    // 0x04-0x06: bsod
                    // 0x07: The GTS is very crowded now. Please try again later (13261). (and it boots you)
                    // 0x08: That Pokémon may not be offered for trade (13268)!
                    // 0x09: That Pokémon may not be offered for trade (13269)!
                    // 0x0a: That Pokémon may not be offered for trade (13270)!
                    // 0x0b: That Pokémon may not be offered for trade (13271)!
                    // 0x0c: That Pokémon may not be offered for trade (13266)!
                    // 0x0d: That Pokémon may not be offered for trade (13267)!
                    // 0x0e: You were disconnected from the GTS. Error code: 13262 (and it boots you)
                    // 0x0f: bsod
                    response.Write(new byte[] { 0x0c, 0x00 }, 0, 2);
                    break;
                }

                // the following two fields are blank in the uploaded record.
                // The server must provide them instead.
                record.TimeDeposited = DateTime.UtcNow;
                record.TimeExchanged = null;
                record.PID           = pid;

                session.Tag = record;
                // todo: delete any other post.asp sessions registered under this PID

                response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
            } break;

            case "/syachi2ds/web/worldexchange/post_finish.asp":
            {
                SessionManager.Remove(session);

                if (request.Length != 8)
                {
                    ShowError(context, 400);
                    return;
                }

                // find a matching session which contains our record
                GamestatsSession prevSession = SessionManager.FindSession(pid, "/syachi2ds/web/worldexchange/post.asp");
                if (prevSession == null)
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                    return;
                }

                SessionManager.Remove(prevSession);
                if (prevSession.Tag == null)
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                    return;
                }
                AssertHelper.Assert(prevSession.Tag is GtsRecord5);
                GtsRecord5 record = (GtsRecord5)prevSession.Tag;

                if (Database.Instance.GtsDepositPokemon5(record))
                {
                    // todo: invalidate cache
                    //manager.RefreshStats();
                    response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
                }
                else
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                }
            } break;

            // the search request has a funny bit string request of search terms
            // and just returns a chunk of records end to end.
            case "/syachi2ds/web/worldexchange/search.asp":
            {
                SessionManager.Remove(session);

                if (request.Length < 7 || request.Length > 8)
                {
                    ShowError(context, 400);
                    return;
                }

                int resultsCount = (int)request[6];

                ushort species = BitConverter.ToUInt16(request, 0);
                if (species < 1)
                {
                    ShowError(context, 400);
                    return;
                }

                response.Write(new byte[] { 0x01, 0x00 }, 0, 2);

                if (resultsCount < 1)
                {
                    break;                       // optimize away requests for no rows
                }
                Genders gender   = (Genders)request[2];
                byte    minLevel = request[3];
                byte    maxLevel = request[4];
                // byte 5 unknown
                byte country = 0;
                if (request.Length > 7)
                {
                    country = request[7];
                }

                if (resultsCount > 7)
                {
                    resultsCount = 7;                       // stop DDOS
                }
                GtsRecord5[] records = Database.Instance.GtsSearch5(pokedex, pid, species, gender, minLevel, maxLevel, country, resultsCount);
                foreach (GtsRecord5 record in records)
                {
                    response.Write(record.Save(), 0, 296);
                }

                Database.Instance.GtsSetLastSearch5(pid);
            } break;

            // the exchange request uploads a record of the exchangee pokemon
            // plus the desired PID to trade for at the very end.
            case "/syachi2ds/web/worldexchange/exchange.asp":
            {
                if (request.Length != 432)
                {
                    SessionManager.Remove(session);
                    ShowError(context, 400);
                    return;
                }

                byte[] uploadData = new byte[296];
                Array.Copy(request, 0, uploadData, 0, 296);
                GtsRecord5 upload = new GtsRecord5(pokedex, uploadData);
                upload.IsExchanged = 0;
                int        targetPid  = BitConverter.ToInt32(request, 296);
                GtsRecord5 result     = Database.Instance.GtsDataForUser5(pokedex, targetPid);
                DateTime?  searchTime = Database.Instance.GtsGetLastSearch5(pid);

                if (result == null || searchTime == null ||
                    result.TimeDeposited > (DateTime)searchTime ||     // If this condition is met, it means the pokemon in the system is DIFFERENT from the one the user is trying to trade for, ie. it was deposited AFTER the user did their search. The one the user wants was either taken back or traded.
                    result.IsExchanged != 0)
                {
                    // Pokémon is traded (or was never here to begin with)
                    SessionManager.Remove(session);
                    response.Write(new byte[] { 0x02, 0x00 }, 0, 2);
                    break;
                }

                // enforce request requirements server side
                if (!upload.Validate() || !upload.CanTrade(result))
                {
                    // todo: find the correct codes for these
                    SessionManager.Remove(session);

                    // responses:
                    // 0x00-0x01: bsod
                    // 0x02: Unfortunately, it was traded to another Trainer.
                    // 0x03-0x07: bsod
                    // 0x08: That Pokémon may not be offered for trade (13268)!
                    // 0x09: That Pokémon may not be offered for trade (13269)!
                    // 0x0a: That Pokémon may not be offered for trade (13270)!
                    // 0x0b: That Pokémon may not be offered for trade (13271)!
                    // 0x0c: That Pokémon may not be offered for trade (13266)!
                    // 0x0d: That Pokémon may not be offered for trade (13267)!
                    // 0x0e: You were disconnected from the GTS. Error code: 13262
                    // 0x0f: bsod
                    response.Write(new byte[] { 0x0c, 0x00 }, 0, 2);
                    return;
                }

                object[] tag = new GtsRecord5[2];
                tag[0]      = upload;
                tag[1]      = result;
                session.Tag = tag;

                GtsRecord5 tradedResult = result.Clone();
                tradedResult.FlagTraded(upload);     // only real purpose is to generate a proper response

                // todo: we need a mechanism to "reserve" a pokemon being traded at this
                // point in the process, but be able to relinquish it if exchange_finish
                // never happens.
                // Currently, if two people try to take the same pokemon, it will appear
                // to work for both but then fail for the second after they've saved
                // their game. This causes a hard crash and a "save file is corrupt,
                // "previous will be loaded" error when restarting.
                // the reservation can be done in application state and has no reason
                // to touch the database. (exchange_finish won't work anyway if application
                // state is lost.)

                response.Write(result.Save(), 0, 296);
            } break;

            case "/syachi2ds/web/worldexchange/exchange_finish.asp":
            {
                SessionManager.Remove(session);

                if (request.Length != 8)
                {
                    ShowError(context, 400);
                    return;
                }

                // find a matching session which contains our record
                GamestatsSession prevSession = SessionManager.FindSession(pid, "/syachi2ds/web/worldexchange/exchange.asp");
                if (prevSession == null)
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                    return;
                }

                SessionManager.Remove(prevSession);
                if (prevSession.Tag == null)
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                    return;
                }
                AssertHelper.Assert(prevSession.Tag is GtsRecord5[]);
                GtsRecord5[] tag = (GtsRecord5[])prevSession.Tag;
                AssertHelper.Assert(tag.Length == 2);

                GtsRecord5 upload = (GtsRecord5)tag[0];
                GtsRecord5 result = (GtsRecord5)tag[1];

                if (Database.Instance.GtsTradePokemon5(upload, result, pid))
                {
                    response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
                }
                else
                {
                    response.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                }
            } break;
                #endregion

                #region Battle Subway
            case "/syachi2ds/web/battletower/info.asp":
                SessionManager.Remove(session);

                // Probably an availability/status code.
                // todo: See how the game reacts to various values.
                response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
                break;

            case "/syachi2ds/web/battletower/roomnum.asp":
                SessionManager.Remove(session);

                //byte rank = data[0x00];
                response.Write(new byte[] { 0x32, 0x00 }, 0, 2);
                break;

            case "/syachi2ds/web/battletower/download.asp":
            {
                SessionManager.Remove(session);

                if (request.Length != 2)
                {
                    ShowError(context, 400);
                    return;
                }

                byte rank    = request[0];
                byte roomNum = request[1];

                if (rank > 9 || roomNum > 49)
                {
                    ShowError(context, 400);
                    return;
                }

                BattleSubwayRecord5[]  opponents = Database.Instance.BattleSubwayGetOpponents5(pid, rank, roomNum);
                BattleSubwayProfile5[] leaders   = Database.Instance.BattleSubwayGetLeaders5(rank, roomNum);

                if (opponents.Length != 7)
                {
                    // todo: Implement fake trainers on Gen5 too.
                    ShowError(context, 500);
                    return;
                }

                foreach (BattleSubwayRecord5 record in opponents)
                {
                    response.Write(record.Save(), 0, 240);
                }

                foreach (BattleSubwayProfile5 leader in leaders)
                {
                    response.Write(leader.Save(), 0, 34);
                }
            } break;

            case "/syachi2ds/web/battletower/upload.asp":
            {
                SessionManager.Remove(session);

                if (request.Length != 388)
                {
                    ShowError(context, 400);
                    return;
                }

                BattleSubwayRecord5 record = new BattleSubwayRecord5(request, 0);

                record.Rank       = request[0xf0];
                record.RoomNum    = request[0xf1];
                record.BattlesWon = request[0xf2];
                record.Unknown4   = new byte[5];
                Array.Copy(request, 0xf3, record.Unknown4, 0, 5);
                record.Unknown5 = BitConverter.ToUInt64(request, 0xf8);

                // todo: Check pkvldtprod signature and/or revalidate

                // todo: Do we want to store their record anyway if they lost the first round?
                if (record.BattlesWon > 0)
                {
                    Database.Instance.BattleSubwayUpdateRecord5(record);
                }
                if (record.BattlesWon == 7)
                {
                    Database.Instance.BattleSubwayAddLeader5(record);
                }

                response.Write(new byte[] { 0x01, 0x00 }, 0, 2);
            } break;

                #endregion
            }
        }
Exemple #23
0
        public void TestWeatherTile()
        {
            TileImageSource backgroundImage = new TileImageSource(BACKGROUND_IMAGE_MOSTLY_CLOUDY);
            int             overlay         = 30;

            TileBindingContentAdaptive smallContent = new TileBindingContentAdaptive()
            {
                TextStacking    = TileTextStacking.Center,
                BackgroundImage = new TileBackgroundImage()
                {
                    Source = backgroundImage, Overlay = overlay
                },
                Children =
                {
                    new TileText()
                    {
                        Text  = "Mon",
                        Style = TileTextStyle.Body,
                        Align = TileTextAlign.Center
                    },

                    new TileText()
                    {
                        Text  = "63°",
                        Style = TileTextStyle.Base,
                        Align = TileTextAlign.Center
                    }
                }
            };


            TileBindingContentAdaptive mediumContent = new TileBindingContentAdaptive()
            {
                BackgroundImage = new TileBackgroundImage()
                {
                    Source = backgroundImage, Overlay = overlay
                },
                Children =
                {
                    new TileGroup()
                    {
                        Children =
                        {
                            GenerateMediumSubgroup("Mon", IMAGE_MOSTLY_CLOUDY, 63, 42),

                            GenerateMediumSubgroup("Tue", IMAGE_CLOUDY,        57, 38)
                        }
                    }
                }
            };



            TileBindingContentAdaptive wideContent = new TileBindingContentAdaptive()
            {
                BackgroundImage = new TileBackgroundImage()
                {
                    Source = backgroundImage, Overlay = overlay
                },
                Children =
                {
                    new TileGroup()
                    {
                        Children =
                        {
                            GenerateWideSubgroup("Mon", IMAGE_MOSTLY_CLOUDY, 63, 42),

                            GenerateWideSubgroup("Tue", IMAGE_CLOUDY,        57, 38),

                            GenerateWideSubgroup("Wed", IMAGE_SUNNY,         59, 43),

                            GenerateWideSubgroup("Thu", IMAGE_SUNNY,         62, 42),

                            GenerateWideSubgroup("Fri", IMAGE_SUNNY,         71, 66)
                        }
                    }
                }
            };



            TileBindingContentAdaptive largeContent = new TileBindingContentAdaptive()
            {
                BackgroundImage = new TileBackgroundImage()
                {
                    Source = backgroundImage, Overlay = overlay
                },
                Children =
                {
                    new TileGroup()
                    {
                        Children =
                        {
                            new TileSubgroup()
                            {
                                Weight   = 30,
                                Children =
                                {
                                    new TileImage()
                                    {
                                        Source = new TileImageSource(IMAGE_MOSTLY_CLOUDY)
                                    }
                                }
                            },

                            new TileSubgroup()
                            {
                                Children =
                                {
                                    new TileText()
                                    {
                                        Text  = "Monday",
                                        Style = TileTextStyle.Base
                                    },

                                    new TileText()
                                    {
                                        Text = "63° / 42°"
                                    },

                                    new TileText()
                                    {
                                        Text  = "20% chance of rain",
                                        Style = TileTextStyle.CaptionSubtle
                                    },

                                    new TileText()
                                    {
                                        Text  = "Winds 5 mph NE",
                                        Style = TileTextStyle.CaptionSubtle
                                    }
                                }
                            }
                        }
                    },

                    // For spacing
                    new TileText(),

                    new TileGroup()
                    {
                        Children =
                        {
                            GenerateLargeSubgroup("Tue", IMAGE_CLOUDY, 57, 38),

                            GenerateLargeSubgroup("Wed", IMAGE_SUNNY,  59, 43),

                            GenerateLargeSubgroup("Thu", IMAGE_SUNNY,  62, 42),

                            GenerateLargeSubgroup("Fri", IMAGE_SUNNY,  71, 66)
                        }
                    }
                }
            };



            TileContent content = new TileContent()
            {
                Visual = new TileVisual()
                {
                    DisplayName = "Seattle",

                    TileSmall = new TileBinding()
                    {
                        Content = smallContent
                    },

                    TileMedium = new TileBinding()
                    {
                        Content  = mediumContent,
                        Branding = TileBranding.Name
                    },

                    TileWide = new TileBinding()
                    {
                        Content  = wideContent,
                        Branding = TileBranding.NameAndLogo
                    },

                    TileLarge = new TileBinding()
                    {
                        Content  = largeContent,
                        Branding = TileBranding.NameAndLogo
                    }
                }
            };



            string expectedPayload = $@"<?xml version=""1.0"" encoding=""utf-8""?><tile><visual displayName=""Seattle""><binding template=""TileSmall"" hint-overlay=""30"" hint-textStacking=""center"">{GenerateStringBackgroundImage()}<text hint-align=""center"" hint-style=""body"">Mon</text><text hint-align=""center"" hint-style=""base"">63°</text></binding><binding template=""TileMedium"" branding=""name"" hint-overlay=""30"">{GenerateStringBackgroundImage()}<group>";

            // Medium tile subgroups
            expectedPayload += GenerateStringMediumSubgroup("Mon", IMAGE_MOSTLY_CLOUDY, 63, 42);
            expectedPayload += GenerateStringMediumSubgroup("Tue", IMAGE_CLOUDY, 57, 38);

            expectedPayload += "</group></binding>";


            // Wide tile
            expectedPayload += @"<binding template=""TileWide"" branding=""nameAndLogo"" hint-overlay=""30"">";
            expectedPayload += GenerateStringBackgroundImage();
            expectedPayload += "<group>";

            // Wide tile subgroups
            expectedPayload += GenerateStringWideSubgroup("Mon", IMAGE_MOSTLY_CLOUDY, 63, 42);
            expectedPayload += GenerateStringWideSubgroup("Tue", IMAGE_CLOUDY, 57, 38);
            expectedPayload += GenerateStringWideSubgroup("Wed", IMAGE_SUNNY, 59, 43);
            expectedPayload += GenerateStringWideSubgroup("Thu", IMAGE_SUNNY, 62, 42);
            expectedPayload += GenerateStringWideSubgroup("Fri", IMAGE_SUNNY, 71, 66);

            expectedPayload += "</group></binding>";



            // Large tile
            expectedPayload += @"<binding template=""TileLarge"" branding=""nameAndLogo"" hint-overlay=""30"">";
            expectedPayload += GenerateStringBackgroundImage();
            expectedPayload += $@"<group><subgroup hint-weight=""30""><image src=""{IMAGE_MOSTLY_CLOUDY}"" /></subgroup><subgroup><text hint-style=""base"">Monday</text><text>63° / 42°</text><text hint-style=""captionSubtle"">20% chance of rain</text><text hint-style=""captionSubtle"">Winds 5 mph NE</text></subgroup></group>";

            expectedPayload += "<text />";
            expectedPayload += "<group>";

            // Large tile subgroups
            expectedPayload += GenerateStringLargeSubgroup("Tue", IMAGE_CLOUDY, 57, 38);
            expectedPayload += GenerateStringLargeSubgroup("Wed", IMAGE_SUNNY, 59, 43);
            expectedPayload += GenerateStringLargeSubgroup("Thu", IMAGE_SUNNY, 62, 42);
            expectedPayload += GenerateStringLargeSubgroup("Fri", IMAGE_SUNNY, 71, 66);

            expectedPayload += "</group></binding></visual></tile>";


            string actualPayload = content.GetContent();

            AssertHelper.AssertXml(expectedPayload, actualPayload);
            //Assert.AreEqual(expectedPayload, actualPayload);
        }
Exemple #24
0
        public async void UserExamDetailsTests()
        {
            var client = httpClientFactory.CreateClient();
            var data   = new UserExamData(client);

            client.Unauthorize();
            var linkUser1PrivateUserExam = $"/userexams/{data.User1PrivateUserExam.Item3.Id}";
            var linkUser1PublicUserExam  = $"/userexams/{data.User1PublicUserExam.Item3.Id}";
            var linkUser1PublicUserExam2 = $"/userexams/{data.User1PublicUserExam2.Item3.Id}";
            var linkUser2PrivateUserExam = $"/userexams/{data.User2PrivateUserExam.Item3.Id}";
            var linkUser2PublicUserExam  = $"/userexams/{data.User2PublicUserExam.Item3.Id}";
            var linkUser2PublicUserExam2 = $"/userexams/{data.User2PublicUserExam2.Item3.Id}";

            await client.GetUnauthorized(linkUser1PrivateUserExam);

            client.Authorize(data.User1PrivateUserExam.Item1.Token);

            var userExam = await client.GetUserExamSuccesfully(linkUser1PrivateUserExam);

            AssertHelper.AssertEqual(userExam, data.User1PrivateUserExam.Item3);

            userExam = await client.GetUserExamSuccesfully(linkUser1PublicUserExam);

            AssertHelper.AssertEqual(userExam, data.User1PublicUserExam.Item3);

            userExam = await client.GetUserExamSuccesfully(linkUser1PublicUserExam2);

            AssertHelper.AssertEqual(userExam, data.User1PublicUserExam2.Item3);

            await client.GetNotFound(linkUser2PrivateUserExam);

            await client.GetNotFound(linkUser2PublicUserExam);

            await client.GetNotFound(linkUser2PublicUserExam2);

            client.Authorize(data.User2PrivateUserExam.Item1.Token);

            await client.GetNotFound(linkUser1PrivateUserExam);

            await client.GetNotFound(linkUser1PublicUserExam);

            await client.GetNotFound(linkUser1PublicUserExam2);

            userExam = await client.GetUserExamSuccesfully(linkUser2PrivateUserExam);

            AssertHelper.AssertEqual(userExam, data.User2PrivateUserExam.Item3);

            userExam = await client.GetUserExamSuccesfully(linkUser2PublicUserExam);

            AssertHelper.AssertEqual(userExam, data.User2PublicUserExam.Item3);

            userExam = await client.GetUserExamSuccesfully(linkUser2PublicUserExam2);

            AssertHelper.AssertEqual(userExam, data.User2PublicUserExam2.Item3);

            //include exam
            var includeExams = "?includeExams=true";

            userExam = await client.GetUserExamSuccesfully($"{linkUser2PrivateUserExam}{includeExams}");

            AssertHelper.AssertEqual(userExam, data.User2PrivateUserExam.Item3, true);

            userExam = await client.GetUserExamSuccesfully($"{linkUser2PublicUserExam}{includeExams}");

            AssertHelper.AssertEqual(userExam, data.User2PublicUserExam.Item3, true);

            userExam = await client.GetUserExamSuccesfully($"{linkUser2PublicUserExam2}{includeExams}");

            AssertHelper.AssertEqual(userExam, data.User2PublicUserExam2.Item3, true);
        }
Exemple #25
0
 public void Test_GetItems_Validate()
 {
     AssertHelper.Throws <InvalidOperationException>(() => {
         Enum.GetItems <Sample>();
     }, "类型 Bing.Tests.Samples.Sample 不是枚举");
 }
Exemple #26
0
 public void TypeBasedOverrideNullCheckForResolverOverride()
 {
     AssertHelper.ThrowsException <ArgumentNullException>(() => new TypeBasedOverride(typeof(TypeToInject2ForTypeOverride), null));
 }
Exemple #27
0
 public void Test_Validate_1()
 {
     _builder.Select("a");
     AssertHelper.Throws <InvalidOperationException>(() => _builder.ToSql());
 }
 public void RegexValidationTest()
 {
     _control.RegexValidation = "test";
     AssertHelper.ThrowsException <ArgumentException>(() => _control.RegexValidation = "invalid");
 }
Exemple #29
0
 public void DefaultZoomsTest()
 {
     AssertHelper.SequenceEqual(new[] { "200%", "150%", "125%", "100%", "75%", "50%" }, zoomViewModel.DefaultZooms);
 }
Exemple #30
0
 void InternalTest(int[] nums, int[] expected)
 {
     MoveZeroes.Solve(nums);
     AssertHelper.AssertArrays(expected, nums);
 }
Exemple #31
0
        private async Task TestFeedEvaluationFeedTask(ConcurrentStack<FeedModel> feeds, SourceModel source, LogEntry sourceLogEntry, AssertHelper assertHelper, bool testArticles = false)
        {
            FeedModel feed;
            while (feeds.TryPop(out feed))
            {
                var feedLogEntry = new LogEntry()
                {
                    Content = "Testing " + feed.Name + " (" + feed.Url + ")"
                };

                var msh = ArticleHelper.GetMediaSource(source.Source, SimpleIoc.Default.GetInstance<IThemeRepository>());
                var sqs = SimpleIoc.Default.GetInstance<ISqliteService>();
                var ids = SimpleIoc.Default.GetInstance<IImageDownloadService>();
                var newArticles = await msh.EvaluateFeed(feed);
                await SaveHelper.SaveFeed(feed, newArticles, sqs, ids);

                foreach (var articleModel in newArticles)
                {
                    var articleLogEntry = new LogEntry()
                    {
                        Content = "Testing " + articleModel.Title + " (" + articleModel.LogicUri + ", " + articleModel.PublicUri + ")"
                    };
                    articleModel.Feed = feed;

                    await SaveHelper.SaveArticle(articleModel, sqs);
                    await SaveHelper.SaveArticleLeadImage(articleModel, sqs, true);
                    await SaveHelper.SaveArticleContent(articleModel, sqs, true);


                    assertHelper.TestFeedArticleProperties(articleModel, articleLogEntry);

                    if (articleModel.LoadingState != LoadingState.Loaded && !await msh.EvaluateArticle(articleModel))
                    {
                        articleLogEntry.LogEntries.Add(new LogEntry()
                        {
                            Content = "Evaluation failed!",
                            IsFaillure = true
                        });
                    }
                    else
                    {
                        articleModel.LoadingState = LoadingState.Loaded;
                        assertHelper.TestFullArticleProperties(articleModel, articleLogEntry);
                    }

                    feedLogEntry.LogEntries.Add(articleLogEntry);
                }

                sourceLogEntry.LogEntries.Add(feedLogEntry);
            }
        }
Exemple #32
0
 public void WhenQueryingAll_ThenThrowsNotSupportedException()
 {
     AssertHelper.Throws <NotSupportedException>(() => Mocks.Of <IFoo>().All(x => x.Value == "Foo"));
 }