public void SerializeExample(UUnitTestContext testContext)
        {
            TestSuiteReport[] actualSuites = JsonWrapper.DeserializeObject <TestSuiteReport[]>(EXAMPLE_JSON);
            testContext.NotNull(actualSuites);

            foreach (var expectedTestName in EXPECTED_TESTS)
            {
                var testFound = false;
                foreach (var suite in actualSuites)
                {
                    foreach (var test in suite.testResults)
                    {
                        if (test.name == expectedTestName)
                        {
                            testFound = true;
                            break;
                        }
                    }
                    testContext.IntEquals(suite.tests, EXPECTED_TESTS.Length, "Total tests does not match expected {0}, {1}");
                }
                testContext.True(testFound, "Test not found: " + expectedTestName);
            }

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#2
0
        void JsonTimeStampHandlesAllFormats(UUnitTestContext testContext)
        {
            string       expectedJson, actualJson;
            DateTime     expectedTime;
            ObjWithTimes actualObj;

            for (var i = 0; i < _examples.Length; i++)
            {
                // Define the time deserialization expectation
                testContext.True(DateTime.TryParseExact(_examples[i], PlayFabUtil._defaultDateTimeFormats, CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out expectedTime), "Index: " + i + "/" + _examples.Length + ", " + _examples[i]);

                // De-serialize the time using json
                expectedJson = "{\"timestamp\":\"" + _examples[i] + "\"}"; // We are provided a json string with every random time format
                actualObj    = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject <ObjWithTimes>(expectedJson);
                actualJson   = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(actualObj);

                if (i == PlayFabUtil.DEFAULT_UTC_OUTPUT_INDEX) // This is the only case where the json input will match the json output
                {
                    testContext.StringEquals(expectedJson, actualJson);
                }

                // Verify that the times match
                var diff = (expectedTime - actualObj.timestamp).TotalSeconds; // We expect that we have parsed the time correctly according to expectations
                testContext.True(diff < 1,
                                 "\nActual time: " + actualObj.timestamp + " vs Expected time: " + expectedTime + ", diff: " + diff +
                                 "\nActual json: " + actualJson + " vs Expected json: " + expectedJson
                                 );
            }
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#3
0
    public void EmailPasswordLoginSuccess(UUnitTestContext testContext)
    {
        const string email    = "*****@*****.**";
        const string password = "******";
        const string username = "******";

        _emailAuthService          = new PlayFabAuthService();
        _emailAuthService.Email    = email;
        _emailAuthService.Password = password;
        _emailAuthService.Username = username;

        _emailAuthService.OnLoginSuccess += (success) =>
        {
            testContext.True(!string.IsNullOrEmpty(success.PlayFabId));
            testContext.NotNull(_emailAuthService.IsClientLoggedIn());
            testContext.EndTest(UUnitFinishState.PASSED, "Email & password auth success. " + success.PlayFabId);
        };
        _emailAuthService.OnPlayFabError += (error) =>
        {
            testContext.Fail("Email & password auth failed with error: " + error.GenerateErrorReport());
        };
        _emailAuthService.OnDisplayAuthentication += () =>
        {
            testContext.Fail("Email & password auth failed.");
        };
        _emailAuthService.Authenticate(AuthTypes.EmailPassword);
    }
 private void WaitForExpectedMessages(UUnitTestContext testContext)
 {
     if (_expectedMessages.Count == 0 && _expectedCustom.Count == 0)
     {
         _messagesTested = true;
         testContext.EndTest(UUnitFinishState.PASSED, null);
     }
     if (DateTime.UtcNow > testContext.StartTime + TimeSpan.FromSeconds(TestExpire))
     {
         var sb = new StringBuilder();
         if (_expectedMessages.Count > 0)
         {
             sb.Append(_expectedMessages.Count).Append(" Missing Messages: ");
             foreach (var eachMsg in _expectedMessages)
             {
                 sb.Append(eachMsg).Append(",");
             }
             sb.Length -= 1;
         }
         if (_expectedCustom.Count > 0)
         {
             sb.Append(_expectedCustom.Count).Append("\nMissing Custom: ");
             foreach (var eachMsg in _expectedCustom)
             {
                 sb.Append(eachMsg).Append(",");
             }
             sb.Length -= 1;
         }
         testContext.Fail(sb.ToString());
     }
 }
示例#5
0
 public void PlayStreamServerConnectionTest(UUnitTestContext testContext)
 {
     PlayFabPlayStreamAPI.Start();
     PlayFabPlayStreamAPI.OnSubscribed += () =>
     {
         testContext.EndTest(UUnitFinishState.PASSED, null);
     };
     PlayFabPlayStreamAPI.OnFailed += error =>
     {
         testContext.EndTest(UUnitFinishState.FAILED, error.Message);
     };
     PlayFabPlayStreamAPI.OnError += error =>
     {
         testContext.EndTest(UUnitFinishState.FAILED, error.StackTrace);
     };
 }
    public async void WriteOneDSEventsAsync(UUnitTestContext testContext)
#endif
    {
        var event1 = new PlayFabEvent()
        {
            Name = "Event_1", EventType = PlayFabEventType.Lightweight
        };

        event1.SetProperty("Prop-A", true);
        event1.SetProperty("Prop-B", "hello");
        event1.SetProperty("Prop-C", 123);

        var event2 = new PlayFabEvent()
        {
            Name = "Event_2", EventType = PlayFabEventType.Lightweight
        };

        event2.SetProperty("Prop-A", false);
        event2.SetProperty("Prop-B", "good-bye");
        event2.SetProperty("Prop-C", 456);

        var request = new WriteEventsRequest
        {
            Events = new List <EventContents>
            {
                event1.EventContents,
                event2.EventContents
            }
        };

        var oneDSEventsApi = new OneDSEventsAPI();

        // get OneDS authentication from PlayFab
        var configRequest = new TelemetryIngestionConfigRequest();

#if TPL_35
        var authTask = OneDSEventsAPI.GetTelemetryIngestionConfigAsync(configRequest).Await();
#else
        var authTask = await OneDSEventsAPI.GetTelemetryIngestionConfigAsync(configRequest);
#endif

        var response = authTask.Result;

        testContext.NotNull(authTask.Result, "Failed to get OneDS authentication info from PlayFab");
        oneDSEventsApi.SetCredentials("o:" + authTask.Result.TenantId, authTask.Result.IngestionKey, authTask.Result.TelemetryJwtToken, authTask.Result.TelemetryJwtHeaderKey, authTask.Result.TelemetryJwtHeaderPrefix);

        // call OneDS events API
#if TPL_35
        var writeTask = oneDSEventsApi.WriteTelemetryEventsAsync(request, null, new Dictionary <string, string>()).Await();
#else
        var writeTask = await oneDSEventsApi.WriteTelemetryEventsAsync(request, null, new Dictionary <string, string>());
#endif

        testContext.NotNull(writeTask);
        testContext.IsNull(writeTask.Error, "Failed to send a batch of custom OneDS events");
        testContext.NotNull(writeTask.Result, "Failed to send a batch of custom OneDS events. Result is null!");
        testContext.EndTest(UUnitFinishState.PASSED, "");
    }
示例#7
0
        public void XmlReadWriteSequence(UUnitTestContext testContext)
        {
            List <TestSuiteReport> xmlReport = JUnitXml.ParseXmlFile(_tempFileFullPath);

            JUnitXml.WriteXmlFile(_tempFileFullPath, xmlReport, true);
            List <TestSuiteReport> xmlReport2 = JUnitXml.ParseXmlFile(_tempFileFullPath);

            testContext.IntEquals(xmlReport.Count, xmlReport2.Count);

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#8
0
    public void LoginWithDeviceId(UUnitTestContext testContext)
    {
        var silentAuth = new PlayFabAuthService();

        silentAuth.OnLoginSuccess += (success) =>
        {
            testContext.StringEquals(_emailAuthService.AuthenticationContext.PlayFabId, success.PlayFabId);
            testContext.EndTest(UUnitFinishState.PASSED, "Silent auth success with playFabId: " + success.PlayFabId);
        };
        silentAuth.OnPlayFabError += (error) =>
        {
            testContext.Fail("Silent auth failed with error: " + error.ErrorMessage);
        };
        silentAuth.Authenticate(AuthTypes.Silent);
    }
示例#9
0
    public void TestSilentLoginAfterUnlink(UUnitTestContext testContext)
    {
        var silentAuth = new PlayFabAuthService();

        silentAuth.OnLoginSuccess += (success) =>
        {
            testContext.True(success.PlayFabId != _emailAuthService.AuthenticationContext.PlayFabId, "Silent auth and email auth playFabIds is match!");
            testContext.EndTest(UUnitFinishState.PASSED, "Silent auth completed as expected. New playFabId: " + success.PlayFabId);
        };
        silentAuth.OnPlayFabError += (error) =>
        {
            testContext.Fail("Silent auth abort with error: " + error.Error.ToString());
        };
        silentAuth.Authenticate(AuthTypes.Silent);
    }
示例#10
0
 public void TestUnLinkDeviceId(UUnitTestContext testContext)
 {
     _emailAuthService.OnPlayFabUnlink += (auth, error) =>
     {
         if (error == null)
         {
             testContext.EndTest(UUnitFinishState.PASSED, "UnLink deviceId success.");
         }
         else
         {
             testContext.Fail("UnLink deviceId failed with error: " + error.ErrorMessage);
         }
     };
     _emailAuthService.Unlink(new AuthKeys {
         AuthType = AuthTypes.Silent
     });
 }
示例#11
0
    public void InvalidEmailPasswordLogin(UUnitTestContext testContext)
    {
        const string password = "******";
        const string username = "******";
        const string email    = "LoginTest.com";

        var authService = new PlayFabAuthService();

        authService.Password = password;
        authService.Username = username;
        authService.Email    = email;

        authService.OnLoginSuccess          += (success) => testContext.Fail("Login fail expected.");
        authService.OnPlayFabError          += (error) => testContext.EndTest(UUnitFinishState.PASSED, "Error handle as expected.");
        authService.OnDisplayAuthentication += () => testContext.Fail("Failed with unknown error.");

        authService.Authenticate(AuthTypes.UsernamePassword);
    }
示例#12
0
        public void EnumConversionTest_Deserialize(UUnitTestContext testContext)
        {
            EnumConversionTestClass expectedObj = new EnumConversionTestClass(), actualObj;

            expectedObj.enumList = new List <testRegion>()
            {
                testRegion.USEast, testRegion.USCentral, testRegion.Japan
            };
            expectedObj.enumArray    = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue    = testRegion.Australia;
            expectedObj.optEnumValue = null;

            string inputJson = "{\"enumList\":[" + ((int)testRegion.USEast) + "," + ((int)testRegion.USCentral) + "," + ((int)testRegion.Japan) + "],\"enumArray\":[" + ((int)testRegion.USEast) + "," + ((int)testRegion.USCentral) + "," + ((int)testRegion.Japan) + "],\"enumValue\":" + ((int)testRegion.Australia) + "}";

            actualObj = JsonWrapper.DeserializeObject <EnumConversionTestClass>(inputJson, PlayFabUtil.ApiSerializerStrategy);
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#13
0
 public void LinkDeviceToAccountSuccess(UUnitTestContext testContext)
 {
     _emailAuthService.ForceLink      = true;
     _emailAuthService.OnPlayFabLink += (auth, error) =>
     {
         if (error == null)
         {
             testContext.EndTest(UUnitFinishState.PASSED, "Link deviceId success.");
         }
         else
         {
             testContext.Fail("Link deviceId failed with error: " + error.GenerateErrorReport());
         }
     };
     _emailAuthService.Link(new AuthKeys {
         AuthType = AuthTypes.Silent
     });
 }
示例#14
0
        public void EnumConversionTest_Deserialize(UUnitTestContext testContext)
        {
            EnumConversionTestClass expectedObj = new EnumConversionTestClass(), actualObj;

            expectedObj.enumList = new List <testRegion>()
            {
                testRegion.USEast, testRegion.USCentral, testRegion.Japan
            };
            expectedObj.enumArray    = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue    = testRegion.Australia;
            expectedObj.optEnumValue = null;

            var inputJson = "{\"enumList\":[" + ((int)testRegion.USEast) + "," + ((int)testRegion.USCentral) + "," + ((int)testRegion.Japan) + "],\"enumArray\":[" + ((int)testRegion.USEast) + "," + ((int)testRegion.USCentral) + "," + ((int)testRegion.Japan) + "],\"enumValue\":" + ((int)testRegion.Australia) + "}";

            actualObj = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject <EnumConversionTestClass>(inputJson);
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
        /// <summary>
        /// Utility for tests to pass as soon as registration is successful
        /// On the first successful registration, this will piggyback some tests that can only occur on a successful registration
        /// </summary>
        /// <param name="testContext"></param>
        protected void PassOnSuccessfulRegistration(UUnitTestContext testContext)
        {
            if (_pushRegisterApiSuccessful)
            {
                testContext.True(PlayFabAndroidPushPlugin.IsPlayServicesAvailable(), "This test should have made Play Services available");

                if (!_messagesTested)
                {
                    PlayFabAndroidPushPlugin.AlwaysShowOnNotificationBar(false); // For the purpose of this test, hide the notifications from the device notification tray
                    SendImmediateNotificationsAndWait();
                    SendScheduledNotificationsAndWait();
                    ActiveTick = WaitForExpectedMessages;
                }
                else
                {
                    testContext.EndTest(UUnitFinishState.PASSED, null);
                }
            }
        }
示例#16
0
    public void InvalidUnlink(UUnitTestContext testContext)
    {
        var authService = new PlayFabAuthService();

        authService.OnPlayFabUnlink += (auth, error) =>
        {
            if (error != null)
            {
                testContext.EndTest(UUnitFinishState.PASSED, "Error handle as expected. " + error.GenerateErrorReport());
            }
            else
            {
                testContext.Fail("Error expected.");
            }
        };
        authService.Unlink(new AuthKeys {
            AuthType = AuthTypes.Facebook
        });
    }
示例#17
0
        void TimeStampHandlesAllFormats(UUnitTestContext testContext)
        {
            DateTime actualTime;
            var formats = PlayFabUtil._defaultDateTimeFormats;

            for (int i = 0; i < _examples.Length; i++)
            {
                string expectedFormat = i < formats.Length ? formats[i] : "default";
                testContext.True(DateTime.TryParseExact(_examples[i], formats, CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out actualTime), "Index: " + i + "/" + _examples.Length + ", " + _examples[i] + " with " + expectedFormat);
            }

            DateTime expectedTime = DateTime.Now;
            for (int i = 0; i < formats.Length; i++)
            {
                string timeString = expectedTime.ToString(formats[i], CultureInfo.CurrentCulture);
                testContext.True(DateTime.TryParseExact(timeString, formats, CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out actualTime), "Index: " + i + "/" + formats.Length + ", " + formats[i] + " with " + timeString);
                testContext.True((actualTime - expectedTime).TotalSeconds < 1, "Expected: " + expectedTime + " vs actual:" + actualTime);
            }
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#18
0
    public void TestUnlinkedDeviceStatus(UUnitTestContext testContext)
    {
        PlayFabClientAPI.GetAccountInfo(new GetAccountInfoRequest
        {
            AuthenticationContext = _emailAuthService.AuthenticationContext
        }, response =>
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            testContext.IsNull(response.AccountInfo.AndroidDeviceInfo, "Android deviceID should be null!");
#elif UNITY_IPHONE || UNITY_IOS && !UNITY_EDITOR
            testContext.IsNull(response.AccountInfo.IosDeviceInfo, "iOS deviceID should be null!");
#else
            testContext.IsNull(response.AccountInfo.CustomIdInfo, "customID should be null!");
#endif
            testContext.EndTest(UUnitFinishState.PASSED, "DeviceId successfully unlinked!");
        },
                                        (error) =>
        {
            testContext.Fail("GetAccountInfo error: " + error.ErrorMessage);
        });
    }
示例#19
0
    public void TestLinkDeviceIdStatus(UUnitTestContext testContext)
    {
        PlayFabClientAPI.GetAccountInfo(new GetAccountInfoRequest
        {
            AuthenticationContext = _emailAuthService.AuthenticationContext
        }, response =>
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            testContext.StringEquals(response.AccountInfo.AndroidDeviceInfo.AndroidDeviceId, PlayFabSettings.DeviceUniqueIdentifier, "Android deviceID not match!");
#elif UNITY_IPHONE || UNITY_IOS && !UNITY_EDITOR
            testContext.StringEquals(response.AccountInfo.IosDeviceInfo.IosDeviceId, PlayFabSettings.DeviceUniqueIdentifier, "iOS deviceID not match!");
#else
            testContext.StringEquals(response.AccountInfo.CustomIdInfo.CustomId, _emailAuthService.GetOrCreateRememberMeId(), "customId not match!");
#endif
            testContext.EndTest(UUnitFinishState.PASSED, "DeviceId successfully linked!");
        },
                                        (error) =>
        {
            testContext.Fail("GetAccountInfo error: " + error.ErrorMessage);
        });
    }
示例#20
0
        void TimeStampHandlesAllFormats(UUnitTestContext testContext)
        {
            DateTime actualTime;
            var      formats = PlayFabUtil._defaultDateTimeFormats;

            for (var i = 0; i < _examples.Length; i++)
            {
                var expectedFormat = i < formats.Length ? formats[i] : "default";
                testContext.True(DateTime.TryParseExact(_examples[i], formats, CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out actualTime), "Index: " + i + "/" + _examples.Length + ", " + _examples[i] + " with " + expectedFormat);
            }

            var expectedTime = DateTime.Now;

            for (var i = 0; i < formats.Length; i++)
            {
                var timeString = expectedTime.ToString(formats[i], CultureInfo.CurrentCulture);
                testContext.True(DateTime.TryParseExact(timeString, formats, CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out actualTime), "Index: " + i + "/" + formats.Length + ", " + formats[i] + " with " + timeString);
                testContext.True((actualTime - expectedTime).TotalSeconds < 1, "Expected: " + expectedTime + " vs actual:" + actualTime);
            }
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#21
0
        /// <summary>
        /// Verify that:
        ///   CSfunc_GetTestData clears any potential existing data
        ///   CSfunc_SaveTestData adds test data
        ///   CSfunc_TestDataExists can correctly verify both states
        /// </summary>
        // [UUnitTest]
        public void WriteTestSequence(UUnitTestContext testContext)
        {
            bool   functionResult, callResult;
            string getErrorReport, saveErrorReport, fetchErrorReport;

            TestSuiteReport[] testResults;
            object            nullReturn;

            var csListenCmd = new CloudScriptListener();

            // Reset a previous test if relevant
            callResult = csListenCmd.ExecuteCloudScript(CloudScriptListener.CsFuncGetTestData, getRequest, testTitleData.extraHeaders, out testResults, out fetchErrorReport);
            //UUnitAssert.True(callResult, fetchErrorReport);

            // Verify that no data pre-exists
            callResult = csListenCmd.ExecuteCloudScript(CloudScriptListener.CsFuncTestDataExists, getRequest, testTitleData.extraHeaders, out functionResult, out getErrorReport);
            testContext.True(callResult, getErrorReport);
            testContext.False(functionResult, getErrorReport);

            // Save some data
            callResult = csListenCmd.ExecuteCloudScript(CloudScriptListener.CsFuncSaveTestData, saveRequest, testTitleData.extraHeaders, out nullReturn, out saveErrorReport);
            testContext.True(callResult, saveErrorReport);

            // Verify that the saved data exists
            callResult = csListenCmd.ExecuteCloudScript(CloudScriptListener.CsFuncTestDataExists, getRequest, testTitleData.extraHeaders, out functionResult, out getErrorReport);
            testContext.True(callResult, getErrorReport);
            testContext.True(functionResult, saveErrorReport);

            // Fetch that data
            callResult = csListenCmd.ExecuteCloudScript(CloudScriptListener.CsFuncGetTestData, getRequest, testTitleData.extraHeaders, out testResults, out fetchErrorReport);
            testContext.True(callResult, fetchErrorReport);
            testContext.NotNull(testResults, fetchErrorReport);

            // Verify that it was consumed
            callResult = csListenCmd.ExecuteCloudScript(CloudScriptListener.CsFuncTestDataExists, getRequest, testTitleData.extraHeaders, out functionResult, out getErrorReport);
            testContext.True(callResult, getErrorReport);
            testContext.False(functionResult, getErrorReport);

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#22
0
        public void EnumConversionTest_Serialize(UUnitTestContext testContext)
        {
            string expectedJson, actualJson;
            EnumConversionTestClass expectedObj = new EnumConversionTestClass(), actualObj;

            expectedObj.enumList = new List <testRegion>()
            {
                testRegion.USEast, testRegion.USCentral, testRegion.Japan
            };
            expectedObj.enumArray    = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue    = testRegion.Australia;
            expectedObj.optEnumValue = null;

            expectedJson = "{\"enumList\":[\"USEast\",\"USCentral\",\"Japan\"],\"enumArray\":[\"USEast\",\"USCentral\",\"Japan\"],\"enumValue\":\"Australia\",\"optEnumValue\":null}";

            actualObj  = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject <EnumConversionTestClass>(expectedJson);
            actualJson = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(actualObj);

            testContext.StringEquals(expectedJson.Replace(" ", "").Replace("\n", ""), actualJson.Replace(" ", "").Replace("\n", ""));
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#23
0
        public void PassWithMessageJson(UUnitTestContext testContext)
        {
            var readFileName = Path.GetFullPath("../../testPassWithMessage.json");

            testContext.True(File.Exists(readFileName), readFileName);
            var json = File.ReadAllText(readFileName);
            List <TestSuiteReport> testReport = JsonWrapper.DeserializeObject <List <TestSuiteReport> >(json);

            testContext.IntEquals(1, testReport.Count);
            foreach (var eachReport in testReport)
            {
                testContext.IntEquals(0, eachReport.failures);
                testContext.IntEquals(0, eachReport.skipped);
                testContext.NotNull(eachReport.testResults);
                foreach (var eachTest in eachReport.testResults)
                {
                    testContext.True(eachTest.IsXmlSingleLine());
                }
            }

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#24
0
        public void EnumConversionTest_OptionalEnum(UUnitTestContext testContext)
        {
            EnumConversionTestClass expectedObj = new EnumConversionTestClass();

            expectedObj.enumList = new List <testRegion>()
            {
                testRegion.USEast, testRegion.USCentral, testRegion.Japan
            };
            expectedObj.enumArray    = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue    = testRegion.Australia;
            expectedObj.optEnumValue = null;

            var actualJson = JsonWrapper.SerializeObject(expectedObj, PlayFabUtil.ApiSerializerStrategy);
            var actualObj  = JsonWrapper.DeserializeObject <EnumConversionTestClass>(actualJson, PlayFabUtil.ApiSerializerStrategy);

            testContext.ObjEquals(expectedObj, actualObj);

            expectedObj.optEnumValue = testRegion.Brazil;
            actualJson = JsonWrapper.SerializeObject(expectedObj, PlayFabUtil.ApiSerializerStrategy);
            actualObj  = JsonWrapper.DeserializeObject <EnumConversionTestClass>(actualJson, PlayFabUtil.ApiSerializerStrategy);
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#25
0
        public void PassWithMessageXml(UUnitTestContext testContext)
        {
            var readFileName = Path.GetFullPath("../../testPassWithMessage.xml");

            testContext.True(File.Exists(readFileName), readFileName);
            List <TestSuiteReport> inputReport = JUnitXml.ParseXmlFile(readFileName);

            JUnitXml.WriteXmlFile(_tempFileFullPath, inputReport, true);
            List <TestSuiteReport> testReport = JUnitXml.ParseXmlFile(_tempFileFullPath);

            testContext.IntEquals(1, testReport.Count);
            foreach (var eachReport in testReport)
            {
                testContext.IntEquals(0, eachReport.failures);
                testContext.IntEquals(0, eachReport.skipped);
                testContext.NotNull(eachReport.testResults);
                foreach (var eachTest in eachReport.testResults)
                {
                    testContext.True(eachTest.IsXmlSingleLine());
                }
            }

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#26
0
        public void EnumConversionTest_OptionalEnum(UUnitTestContext testContext)
        {
            var expectedObj = new EnumConversionTestClass
            {
                enumList = new List <testRegion>()
                {
                    testRegion.USEast, testRegion.USCentral, testRegion.Japan
                },
                enumArray    = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan },
                enumValue    = testRegion.Australia,
                optEnumValue = null,
            };

            var actualJson = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObj);
            var actualObj  = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject <EnumConversionTestClass>(actualJson);

            testContext.ObjEquals(expectedObj, actualObj);

            expectedObj.optEnumValue = testRegion.Brazil;
            actualJson = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(expectedObj);
            actualObj  = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject <EnumConversionTestClass>(actualJson);
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
    public async void EmitLightweightEventsAsync(UUnitTestContext testContext)
#endif
    {
        // create and set settings for OneDS event pipeline
        var settings = new OneDSEventPipelineSettings();

        settings.BatchSize        = 8;
        settings.BatchFillTimeout = TimeSpan.FromSeconds(1);
        var logger = new DebugLogger();

        // create OneDS event pipeline
        var oneDSPipeline = new OneDSEventPipeline(settings, logger);

        // create custom event API, add the pipeline
        var playFabEventApi = new PlayFabEventAPI(logger);

#pragma warning disable 4014
        playFabEventApi.EventRouter.AddAndStartPipeline(EventPipelineKey.OneDS, oneDSPipeline);
#pragma warning restore 4014

        // create and emit many lightweight events
#if TPL_35
        var results = new List <Task <IPlayFabEmitEventResponse> >();
#else
        var results = new List <Task>();
#endif

        for (int i = 0; i < 50; i++)
        {
            results.AddRange(playFabEventApi.EmitEvent(CreateSamplePlayFabEvent("Event_Custom", PlayFabEventType.Lightweight)));
        }

        // wait when the pipeline finishes sending all events
#if TPL_35
        Task.WhenAll(results).Await();
#else
        await Task.WhenAll(results);
#endif

        // check results
        var sentBatches = new Dictionary <IList <IPlayFabEmitEventRequest>, int>();

        foreach (var result in results)
        {
            testContext.True(result.IsCompleted, "Custom event emission task failed to complete");
            PlayFabEmitEventResponse response = (PlayFabEmitEventResponse)((Task <IPlayFabEmitEventResponse>)result).Result;
            testContext.True(response.EmitEventResult == EmitEventResult.Success, "Custom event emission task failed to succeed");
            testContext.True(response.PlayFabError == null && response.WriteEventsResponse != null, "Custom event failed to be sent");

            if (!sentBatches.ContainsKey(response.Batch))
            {
                sentBatches[response.Batch] = 0;
            }

            sentBatches[response.Batch]++;
        }

        int event8 = 0;
        int event2 = 0;

        foreach (var batch in sentBatches)
        {
            if (batch.Value == 8)
            {
                event8++;
            }
            else if (batch.Value == 2)
            {
                event2++;
            }
        }

        // 6 full batches of 8 events and 1 incomplete batch of 2 events are expected
        testContext.True(event8 == 6, "Wrong number of full batches");
        testContext.True(event2 == 1, "Wrong number of incomplete batches");
        testContext.EndTest(UUnitFinishState.PASSED, null);
    }
示例#28
0
        public void EnumConversionTest_OptionalEnum(UUnitTestContext testContext)
        {
            EnumConversionTestClass expectedObj = new EnumConversionTestClass();
            expectedObj.enumList = new List<testRegion>() { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumArray = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue = testRegion.Australia;
            expectedObj.optEnumValue = null;

            var actualJson = JsonWrapper.SerializeObject(expectedObj, PlayFabUtil.ApiSerializerStrategy);
            var actualObj = JsonWrapper.DeserializeObject<EnumConversionTestClass>(actualJson, PlayFabUtil.ApiSerializerStrategy);
            testContext.ObjEquals(expectedObj, actualObj);

            expectedObj.optEnumValue = testRegion.Brazil;
            actualJson = JsonWrapper.SerializeObject(expectedObj, PlayFabUtil.ApiSerializerStrategy);
            actualObj = JsonWrapper.DeserializeObject<EnumConversionTestClass>(actualJson, PlayFabUtil.ApiSerializerStrategy);
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#29
0
        public void EnumConversionTest_Deserialize(UUnitTestContext testContext)
        {
            EnumConversionTestClass expectedObj = new EnumConversionTestClass(), actualObj;
            expectedObj.enumList = new List<testRegion>() { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumArray = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue = testRegion.Australia;
            expectedObj.optEnumValue = null;

            string inputJson = "{\"enumList\":[" + ((int)testRegion.USEast) + "," + ((int)testRegion.USCentral) + "," + ((int)testRegion.Japan) + "],\"enumArray\":[" + ((int)testRegion.USEast) + "," + ((int)testRegion.USCentral) + "," + ((int)testRegion.Japan) + "],\"enumValue\":" + ((int)testRegion.Australia) + "}";
            actualObj = JsonWrapper.DeserializeObject<EnumConversionTestClass>(inputJson, PlayFabUtil.ApiSerializerStrategy);
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#30
0
        void JsonTimeStampHandlesAllFormats(UUnitTestContext testContext)
        {
            string expectedJson, actualJson;
            DateTime expectedTime;
            ObjWithTimes actualObj = new ObjWithTimes();

            for (int i = 0; i < _examples.Length; i++)
            {
                // Define the time deserialization expectation
                testContext.True(DateTime.TryParseExact(_examples[i], PlayFabUtil._defaultDateTimeFormats, CultureInfo.CurrentCulture, DateTimeStyles.RoundtripKind, out expectedTime), "Index: " + i + "/" + _examples.Length + ", " + _examples[i]);

                // De-serialize the time using json
                expectedJson = "{\"timestamp\":\"" + _examples[i] + "\"}"; // We are provided a json string with every random time format
                actualObj = JsonWrapper.DeserializeObject<ObjWithTimes>(expectedJson, PlayFabUtil.ApiSerializerStrategy);
                actualJson = JsonWrapper.SerializeObject(actualObj, PlayFabUtil.ApiSerializerStrategy);

                if (i == PlayFabUtil.DEFAULT_UTC_OUTPUT_INDEX) // This is the only case where the json input will match the json output
                    testContext.StringEquals(expectedJson, actualJson);

                // Verify that the times match
                double diff = (expectedTime - actualObj.timestamp).TotalSeconds; // We expect that we have parsed the time correctly according to expectations
                testContext.True(diff < 1,
                    "\nActual time: " + actualObj.timestamp + " vs Expected time: " + expectedTime + ", diff: " + diff +
                    "\nActual json: " + actualJson + " vs Expected json: " + expectedJson
                );
            }
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
示例#31
0
        public void UserStatisticsApi(UUnitTestContext testContext)
        {
            if (!TITLE_CAN_UPDATE_SETTINGS)
            {
                testContext.EndTest(UUnitFinishState.SKIPPED, "This title cannot update statistics from the client");
                return;
            }

            var getRequest = new GetUserStatisticsRequest();
            PlayFabClientAPI.GetUserStatistics(getRequest, PlayFabUUnitUtils.ApiCallbackWrapper<GetUserStatisticsResult>(testContext, GetUserStatsCallback1), SharedErrorCallback, testContext);
        }
示例#32
0
        public void EnumConversionTest_Serialize(UUnitTestContext testContext)
        {
            string expectedJson, actualJson;
            EnumConversionTestClass expectedObj = new EnumConversionTestClass(), actualObj;
            expectedObj.enumList = new List<testRegion>() { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumArray = new testRegion[] { testRegion.USEast, testRegion.USCentral, testRegion.Japan };
            expectedObj.enumValue = testRegion.Australia;
            expectedObj.optEnumValue = null;

            expectedJson = "{\"enumList\":[\"USEast\",\"USCentral\",\"Japan\"],\"enumArray\":[\"USEast\",\"USCentral\",\"Japan\"],\"enumValue\":\"Australia\",\"optEnumValue\":null}";

            actualObj = JsonWrapper.DeserializeObject<EnumConversionTestClass>(expectedJson, PlayFabUtil.ApiSerializerStrategy);
            actualJson = JsonWrapper.SerializeObject(actualObj, PlayFabUtil.ApiSerializerStrategy);

            testContext.StringEquals(expectedJson.Replace(" ", "").Replace("\n", ""), actualJson.Replace(" ", "").Replace("\n", ""));
            testContext.ObjEquals(expectedObj, actualObj);
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }