コード例 #1
0
ファイル: MainThread.cs プロジェクト: richfuns/cscore
 private void Awake()
 {
     Log.d("Now initializing MainThread helper");
     AssertV2.IsTrue(mainThreadRef == null || mainThreadRef == Thread.CurrentThread, "MainThread already set to " + mainThreadRef);
     mainThreadRef = Thread.CurrentThread;
     stopWatch     = Stopwatch.StartNew();
 }
コード例 #2
0
ファイル: ResourcesV2.cs プロジェクト: yazici/cscore-1
        /// <summary>
        /// Load a ScriptableObject instance from a Resources subpath, for example:
        ///   MyExampleScriptableObject_Instance1.asset is located in Assets/Ui/Resources/MyFolderX
        ///   -> The path must be "MyFolderX/MyExampleScriptableObject_Instance1"
        /// </summary>
        public static T LoadScriptableObjectInstance <T>(string pathInResourcesFolder) where T : ScriptableObject
        {
            var so = LoadV2 <T>(pathInResourcesFolder);

            AssertV2.IsNotNull(so, "ScriptableObject (" + typeof(T) + ") instance " + pathInResourcesFolder);
            return(so);
        }
コード例 #3
0
 private static IEnumerable <JToken> GetFilteredDiff(JToken diffToExpectedState, Func <JToken, bool> filterAcceptableDiffs)
 {
     return(diffToExpectedState.Children().Skip(1).Filter(problem => {
         AssertV2.AreEqual(1, problem.Count(), "The diff contained not exactly one element");
         return filterAcceptableDiffs(problem.First());
     }));
 }
コード例 #4
0
        public static T GetResult <T>(this UnityWebRequest self, IJsonReader r)
        {
            AssertV2.IsTrue(self.isDone, "web request was not done!");
            if (TypeCheck.AreEqual <T, UnityWebRequest>())
            {
                return((T)(object)self);
            }
            if (typeof(Texture2D).IsCastableTo(typeof(T)))
            {
                AssertV2.IsTrue(self.downloadHandler is DownloadHandlerTexture, "self.downloadHandler was not a DownloadHandlerTexture");
                var h = (DownloadHandlerTexture)self.downloadHandler;
                return((T)(object)h.texture);
            }
            if (TypeCheck.AreEqual <T, Stream>())
            {
                return((T)(object)new MemoryStream(self.downloadHandler.data));
            }
            if (TypeCheck.AreEqual <T, byte[]>())
            {
                return((T)(object)self.downloadHandler.data);
            }
            if (TypeCheck.AreEqual <T, Headers>())
            {
                return((T)(object)self.GetResponseHeadersV2());
            }
            var text = self.downloadHandler.text;

            if (TypeCheck.AreEqual <T, string>())
            {
                return((T)(object)text);
            }
            return(r.Read <T>(text));
        }
コード例 #5
0
        public static double CompareV2(this MagickImage self, MagickImage oldImg, ErrorMetric errorMetric, out MagickImage imgWithDifferences)
        {
            // Check if both images have the same size:
            bool isNewImageSameSizeAsOldImage = oldImg.Width == self.Width && oldImg.Height == self.Height;

            if (!isNewImageSameSizeAsOldImage)
            {
                var  diffSizesWarn = $"Different sizes: OldImage=({oldImg.Width}X{oldImg.Height}) but NewImage=({self.Width}X{self.Height})";
                bool isNewImageAspectRatioSameAsOldImage = self.GetAspectRatio() == oldImg.GetAspectRatio();
                if (isNewImageAspectRatioSameAsOldImage)
                {
                    Log.w(diffSizesWarn);
                    // If aspect ratio matches, resize both images to same size:
                    var minWidth  = Math.Min(oldImg.Width, self.Width);
                    var minHeight = Math.Min(oldImg.Height, self.Height);
                    oldImg.Resize(minWidth, minHeight);
                    self.Resize(minWidth, minHeight);
                }
                else     // Missmatch in image sizes cant be fixed, abort:
                {
                    throw new ArgumentException("Can't compare! " + diffSizesWarn);
                }
            }
            AssertV2.AreEqual(oldImg.Width, self.Width, "RegressionImage.Width");
            AssertV2.AreEqual(oldImg.Height, self.Height, "RegressionImage.Height");
            //return oldImg.Compare(self, out imgWithDifferences);
            imgWithDifferences = new MagickImage();
            return(oldImg.Compare(self, new CompareSettings()
            {
                Metric = errorMetric
            }, imgWithDifferences));
        }
コード例 #6
0
 private static void AssertResponseLooksNormal <T>(UnityWebRequest self, Response <T> resp)
 {
     AssertV2.IsNotNull(self, "WebRequest object was null: " + resp);
     if (self != null)
     {
         AssertV2.IsTrue(self.isDone, "Request never finished: " + resp);
         if (self.isNetworkError)
         {
             Log.w("isNetworkError=true for " + resp);
         }
         if (self.error != null)
         {
             Log.w("error=" + self.error + " for " + resp);
         }
         if (self.isHttpError)
         {
             Log.w("isHttpError=true for " + resp);
         }
         if (self.responseCode < 200 || self.responseCode >= 300)
         {
             Log.w("responseCode=" + self.responseCode + " for " + resp);
         }
         if (self.isNetworkError && self.responseCode == 0 && self.useHttpContinue)
         {
             Log.w("useHttpContinue flag was true, request might work if its set to false");
         }
     }
 }
コード例 #7
0
            public static MergeConflict ToMergeConflict(JProperty prop)
            {
                var res = new MergeConflict();

                res.fieldName = prop.Name;
                if (prop.Value is JObject o)
                {
                    var properties = o.Properties();
                    if (IsArray(properties.First()))
                    {
                        res.specialType = MergeConflict.SPECIAL_TYPE_ARRAY;
                        properties      = properties.Skip(1);
                    }
                    res.conflicts = properties.Map(ToMergeConflict);
                }
                else if (prop.Value is JArray oldAndNewValue)
                {
                    AssertV2.AreEqual(2, oldAndNewValue.Count);
                    res.oldValue = oldAndNewValue[0];
                    res.newValue = oldAndNewValue[1];
                }
                else
                {
                    throw new NotImplementedException("Unhandled type " + prop.Value.GetType() + ":\n" + prop.Value.ToPrettyString());
                }
                return(res);
            }
コード例 #8
0
ファイル: FileExtensions.cs プロジェクト: yazici/cscore-1
        public static bool Rename(this DirectoryInfo self, string newName)
        {
            var target = self.Parent.GetChildDir(newName);

            AssertV2.IsFalse(target.IsNotNullAndExists(), "Already exists: target=" + target.FullPath());
            return(self.MoveToV2(target));
        }
コード例 #9
0
        private IEnumerator AssertNoVisualRegressionCoroutine(string id, StackTrace stacktrace)
        {
            if (id.IsNullOrEmpty())
            {
                throw new ArgumentNullException("Invalid ID passed");
            }

            var idFolder = GetFolderFor(id);
            var oldImg   = idFolder.GetChild("Regression.jpg");
            var newImg   = idFolder.GetChild("Latest.jpg");
            var backup   = idFolder.GetChild("Previous.jpg.backup");

            Config config = LoadConfigFor(idFolder);

            yield return(new WaitForEndOfFrame());

            try {
                Texture2D screenShot = ScreenCapture.CaptureScreenshotAsTexture(config.screenshotUpscaleFactor);
                // Texture2D screenShot = Camera.allCameras.CaptureScreenshot(); // Does not capture UI

                if (newImg.Exists)
                {
                    newImg.CopyToV2(backup, replaceExisting: true);
                }
                screenShot.SaveToJpgFile(newImg, config.screenshotQuality);
                screenShot.Destroy();
            }
            catch (Exception e) {
                Log.w("Could NOT capture screensot: \n" + e);
                yield break;
            }

            try {
                var diffImg = CalculateDiffImage(oldImg, newImg, config.maxAllowedDiff, config.errorMetric);
                if (diffImg != null)
                {
                    var e = $"Visual diff to previous '{id}' detected! To approve an allowed visual change, delete '{oldImg.Name}'";
                    if (!config.customErrorMessage.IsNullOrEmpty())
                    {
                        e = config.customErrorMessage + "/n" + e;
                    }
                    HandleException(config, diffImg, new Error(e, stacktrace));
                }
                else                                                 // No difference between oldImg and newImg
                                                                     // To prevent git from detecting invalid file changes:
                {
                    if (backup.Exists)                               // If there is a backup of newImg..
                    {
                        newImg.DeleteV2();                           // Remove the newly generated version ..
                        backup.Rename(newImg.Name, out FileEntry _); // and replace it with the backup
                    }
                }
                backup.DeleteV2(); // If a backup file was created during the process delete it
                AssertV2.IsTrue(newImg.Exists, "newImg did not exist after AssertNoVisualChange done");
            }
            catch (ArgumentException e) {
                HandleException(config, oldImg, new Error(e.Message, stacktrace));
            }
        }
コード例 #10
0
ファイル: Log.cs プロジェクト: richfuns/cscore
        public static Stopwatch MethodEntered(params object[] args)
        {
#if DEBUG
            var t = new StackFrame(1, true);
            Log.d(" --> " + t.GetMethodName(false), t.AddTo(args));
#endif
            return(AssertV2.TrackTiming());
        }
コード例 #11
0
        public static Texture2D ToTexture2D(this ImageResult self)
        {
            AssertV2.AreEqual(8, self.BitsPerChannel);
            Texture2D tex = new Texture2D(self.Width, self.Height, TextureFormat.RGBA32, false);

            tex.LoadRawTextureData(self.Data);
            tex.Apply();
            return(tex);
        }
コード例 #12
0
        private async Task <bool> RunInternetCheck()
        {
            var newState = await RestFactory.instance.HasInternet();

            await SetHasInet(newState);

            AssertV2.AreEqual(HasInet, newState);
            return(HasInet);
        }
コード例 #13
0
 public static Vector3[] GetWorldCornersV2(this RectTransform self, Vector3[] cache = null)
 {
     if (cache == null)
     {
         cache = new Vector3[4];
     }
     AssertV2.AreEqual(4, cache.Length);
     self.GetWorldCorners(cache);
     return(cache);
 }
コード例 #14
0
 public static FileEntry GetChild(this DirectoryEntry self, string fileName, bool sanitize = true)
 {
     fileName.ThrowErrorIfNullOrEmpty("fileName");
     if (sanitize)
     {
         fileName = Sanitize.SanitizeToFileName(fileName);
     }
     AssertV2.AreEqual(fileName, Sanitize.SanitizeToFileName(fileName));
     return(ResolveFilePath(self, fileName));
 }
コード例 #15
0
ファイル: ZioExtensions.cs プロジェクト: shoshiiran/cscore
 private static bool DeleteV2(FileSystemEntry self, Func <bool> deleteAction)
 {
     if (self.IsNotNullAndExists())
     {
         var res = deleteAction();
         AssertV2.IsFalse(!res || self.Exists, "Still exists: " + self);
         return(res);
     }
     return(false);
 }
コード例 #16
0
 public static DirectoryEntry GetChildDir(this DirectoryEntry self, string subDirName, bool sanitize = true)
 {
     subDirName.ThrowErrorIfNullOrEmpty("subDirName");
     if (sanitize)
     {
         subDirName = Sanitize.SanitizeToDirName(subDirName);
     }
     AssertV2.AreEqual(subDirName, Sanitize.SanitizeToDirName(subDirName));
     return(ResolveDirectoryPath(self, subDirName));
 }
コード例 #17
0
ファイル: FileExtensions.cs プロジェクト: yazici/cscore-1
        public static DirectoryInfo GetChildDir(this DirectoryInfo self, string childFolder, bool assertThatChildMustExist = false)
        {
            var c = new DirectoryInfo(self.FullPath() + childFolder);

            if (assertThatChildMustExist)
            {
                AssertV2.IsTrue(c.IsNotNullAndExists(), "childFolder '" + childFolder + "' doesnt exist! Path=" + c.FullPath());
            }
            return(c);
        }
コード例 #18
0
ファイル: FileExtensions.cs プロジェクト: yazici/cscore-1
 private static bool DeleteV2(FileSystemInfo self, Func <bool> deleteAction)
 {
     if (self != null && self.ExistsV2())
     {
         var res = deleteAction();
         self.Refresh();
         AssertV2.IsFalse(!res || self.ExistsV2(), "Still exists: " + self.FullName);
         return(res);
     }
     return(false);
 }
コード例 #19
0
 private static bool DeleteV2(FileSystemInfo self, Action deleteAction)
 {
     if (self != null && self.Exists)
     {
         deleteAction();
         self.Refresh();
         AssertV2.IsFalse(self.Exists, "Still exists: " + self.FullName);
         return(true);
     }
     return(false);
 }
コード例 #20
0
        /// <summary> Connects a model with a view </summary>
        /// <returns> A task that can be awaited on, that returns the fully setup presenter </returns>
        public static async Task <T> LoadModelIntoView <T>(this Presenter <T> self, T model)
        {
            AssertV2.IsNotNull(self.targetView, "presenter.targetView");
            var name = self.GetType().Name + "_((" + model.GetType().Name + "))";

            AppFlow.TrackEvent(EventConsts.catPresenter, "Load-start:" + name, self, model);
            await self.OnLoad(model);

            AppFlow.TrackEvent(EventConsts.catPresenter, "Load-done:" + name, self, model);
            return(model);
        }
コード例 #21
0
 private static void SetupDownloadAndUploadHanders <T>(UnityWebRequest self, Response <T> resp)
 {
     self.downloadHandler = resp.createDownloadHandler();
     switch (self.method)
     {
     case UnityWebRequest.kHttpVerbPUT:
     case UnityWebRequest.kHttpVerbPOST:
         AssertV2.IsNotNull(self.uploadHandler, "Put/Post-request had no uploadHandler set");
         break;
     }
 }
コード例 #22
0
ファイル: Log.cs プロジェクト: yazici/cscore-1
        public static StopwatchV2 MethodEntered([CallerMemberName] string methodName = null, params object[] args)
        {
#if DEBUG
            args = new StackFrame(1, true).AddTo(args);
#endif
            Log.d(" --> " + methodName, args);
            if (!methodName.IsNullOrEmpty())
            {
                AppFlow.TrackEvent(AppFlow.catMethod, methodName, args);
            }
            return(AssertV2.TrackTiming(methodName));
        }
コード例 #23
0
 public static UnityWebRequest SetRequestHeaders(this UnityWebRequest self, Headers headersToAdd)
 {
     if (!headersToAdd.IsNullOrEmpty())
     {
         foreach (var h in headersToAdd)
         {
             AssertV2.AreEqual(1, h.Value.Count());
             self.SetRequestHeader(h.Key, h.Value.First());
         }
     }
     return(self);
 }
コード例 #24
0
ファイル: ZioExtensions.cs プロジェクト: shoshiiran/cscore
 public static bool MoveToV2(this DirectoryEntry source, DirectoryEntry target, out DirectoryEntry result)
 {
     AssertNotIdentical(source, target);
     AssertV2.IsTrue(source.FileSystem == target.FileSystem, "Moving between different file systems not implemented");
     source.MoveTo(target.Path);
     if (!target.Exists)
     {
         throw new DirectoryNotFoundException("Could not move dir to " + target);
     }
     result = target;
     return(target.Exists);
 }
コード例 #25
0
ファイル: ZioExtensions.cs プロジェクト: shoshiiran/cscore
 public static FileEntry CopyToV2(this FileEntry self, FileEntry target, bool replaceExisting)
 {
     if (self.FileSystem != target.FileSystem)
     {
         using (var t = target.OpenOrCreateForWrite()) {
             t.SetLength(0); // Reset the stream in case it was opened
             using (var s = self.OpenForRead()) { s.CopyTo(t); }
         }
         AssertV2.IsTrue(target.Exists, "Target did not exist after copy to was done: " + target);
         return(target);
     }
     return(self.CopyTo(target.Path, replaceExisting));
 }
コード例 #26
0
ファイル: DateTimeV2.cs プロジェクト: shoshiiran/cscore
        public static DateTime NewDateTimeFromUnixTimestamp(long unixTimeInMs, bool autoCorrectIfPassedInSeconds = true)
        {
            AssertV2.IsTrue(unixTimeInMs > 0, "NewDateTimeFromUnixTimestamp: unixTimeInMs was " + unixTimeInMs);
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var             result     = dtDateTime.AddMilliseconds(unixTimeInMs);

            if (autoCorrectIfPassedInSeconds && result.Year == 1970)
            {
                var correctedDate = NewDateTimeFromUnixTimestamp(unixTimeInMs * 1000, false);
                Log.e("The passed unixTimeInMs was likely passed in seconds instead of milliseconds,"
                      + " it was too small by a factor of *1000, which would result in " + correctedDate.ToReadableString());
                return(correctedDate);
            }
            return(result);
        }
コード例 #27
0
 public static void SaveStream(this FileEntry self, Stream streamToSave, Action <long> onProgress = null)
 {
     AssertV2.AreNotEqual(0, streamToSave.Length, "streamToSave.Length");
     using (var fileStream = self.OpenOrCreateForWrite()) {
         fileStream.SetLength(0); // Reset the stream in case it was opened
         if (onProgress == null)
         {
             streamToSave.CopyTo(fileStream);
         }
         else
         {
             streamToSave.CopyTo(fileStream, onProgress);
         }
     }
 }
コード例 #28
0
ファイル: FileExtensions.cs プロジェクト: cs-util-com/cscore
        public static FileInfo GetChild(this DirectoryInfo self, string fileName, bool assertThatChildMustExist = false, bool sanitize = true)
        {
            fileName.ThrowErrorIfNullOrEmpty("fileName");
            if (sanitize)
            {
                fileName = Sanitize.SanitizeToFileName(fileName);
            }
            AssertV2.AreEqual(fileName, Sanitize.SanitizeToFileName(fileName));
            var c = new FileInfo(self.FullPath() + fileName);

            if (assertThatChildMustExist)
            {
                AssertV2.IsTrue(c.IsNotNullAndExists(), "childFile '" + fileName + "' doesnt exist! Path=" + c.FullPath());
            }
            return(c);
        }
コード例 #29
0
ファイル: FileExtensions.cs プロジェクト: cs-util-com/cscore
        public static DirectoryInfo GetChildDir(this DirectoryInfo self, string subDirName, bool assertThatChildMustExist = false, bool sanitize = true)
        {
            subDirName.ThrowErrorIfNullOrEmpty("subDirName");
            if (sanitize)
            {
                subDirName = Sanitize.SanitizeToDirName(subDirName);
            }
            AssertV2.AreEqual(subDirName, Sanitize.SanitizeToDirName(subDirName));
            var c = new DirectoryInfo(self.FullPath() + subDirName);

            if (assertThatChildMustExist)
            {
                AssertV2.IsTrue(c.IsNotNullAndExists(), "childFolder '" + subDirName + "' doesnt exist! Path=" + c.FullPath());
            }
            return(c);
        }
コード例 #30
0
 public static bool Destroy(this UnityEngine.Object self, bool destroyNextFrame = false)
 {
     if (self == null)
     {
         return(false);
     }
     try { if (destroyNextFrame)
           {
               UnityEngine.Object.Destroy(self);
           }
           else
           {
               GameObject.DestroyImmediate(self);
           } } catch { return(false); }
     AssertV2.IsTrue(destroyNextFrame || self.IsDestroyed(), "gameObject was not destroyed");
     return(true);
 }