Beispiel #1
0
        public void TestOperations()
        {
            BO4E.StaticLogger.Logger = new Microsoft.Extensions.Logging.Debug.DebugLogger("Testlogger", (log, level) => { return(true); });
            string[] files = Directory.GetFiles($"anonymizerTests/masterdata/", "*.json"); //
            foreach (string testFile in files)
            {
                JObject json;
                using (StreamReader r = new StreamReader(testFile))
                {
                    string jsonString = r.ReadToEnd();
                    json = JObject.Parse(jsonString);
                }

                BusinessObject bo;
                using (Anonymizer a = new Anonymizer(new AnonymizerConfiguration()))
                {
                    bo = JsonConvert.DeserializeObject <BusinessObject>(json["input"].ToString());
                    Assert.IsTrue(bo.Equals(a.ApplyOperations <BusinessObject>(bo)));
                }
                AnonymizerConfiguration      ac            = new AnonymizerConfiguration();
                HashSet <AnonymizerApproach> allApproaches = new HashSet <AnonymizerApproach>();;
                Dictionary <string, string>  operations    = JsonConvert.DeserializeObject <Dictionary <string, string> >(((JObject)json["operations"]).ToString());
                //Assert.AreEqual(json["input"].ToString(), resultJobject.ToString(), "Anonymizer without configuration should return the original message");
                foreach (string key in operations.Keys)
                {
                    Enum.TryParse(key, out DataCategory option);
                    Enum.TryParse(operations[key], out AnonymizerApproach approach);
                    Assert.IsNotNull(option, "Option invalid. Check test file " + testFile);
                    Assert.IsNotNull(approach, "Approach invalid, Check test file " + testFile);
                    ac.SetOption(option, approach);
                    allApproaches.Add(approach);
                }
                using (Anonymizer a = new Anonymizer(ac))
                {
                    if (ac.operations.ContainsValue(AnonymizerApproach.ENCRYPT))
                    {
                        X509Certificate2 x509certPubl = new X509Certificate2(X509Certificate2.CreateFromCertFile("anonymizerTests/certificates/publicX509Cert.crt"));
                        a.SetPublicKey(x509certPubl);
                    }
                    if (ac.operations.ContainsValue(AnonymizerApproach.HASH))
                    {
                        byte[] predefinedSalt = new byte[] { 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90 }; // only predefined for test case
                        a.SetHashingSalt(predefinedSalt);
                    }
                    JObject resultJobject = a.ApplyOperations <JObject>(JsonConvert.DeserializeObject <BusinessObject>(json["input"].ToString()));

                    if (allApproaches.Count == 1 && allApproaches.Contains(AnonymizerApproach.ENCRYPT))
                    {
                        // iff the file only contains encryption operations, we simple encrypt it once,
                        // decrypt the cipher text and assert they're equal. This complete reversion
                        // round trip is not possible if any other option like DELETE, REPLACE, HASH etc.
                        // is chosen.
                        AnonymizerConfiguration acInvert = new AnonymizerConfiguration();
                        foreach (string key in operations.Keys)
                        {
                            if (Enum.TryParse(operations[key], out AnonymizerApproach option))
                            {
                                if (Enum.TryParse(key, out DataCategory dc))
                                {
                                    acInvert.SetOption(dc, AnonymizerApproach.DECRYPT);
                                }
                            }
                        }
                        BusinessObject decryptedBo;
                        using (Anonymizer d = new Anonymizer(acInvert))
                        {
                            AsymmetricCipherKeyPair keyPair;
                            using (var reader = File.OpenText(@"anonymizerTests/certificates/privateKey.pem")) // file containing RSA PKCS1 private key
                            {
                                //Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters rpk = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)new PemReader(reader).ReadObject();
                                keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
                            }
                            d.SetPrivateKey(keyPair.Private);
                            decryptedBo = d.ApplyOperations <BusinessObject>(resultJobject);
                        }
                        var    jdp = new JsonDiffPatch(); // https://github.com/wbish/jsondiffpatch.net
                        JToken left, right;
                        left  = JsonHelper.RemoveEmptyChildren(json["input"]);
                        right = JsonHelper.RemoveEmptyChildren(JObject.FromObject(decryptedBo));
                        var    patch             = jdp.Diff(left, right);
                        string additionalMessage = testFile;
                        if (patch != null)
                        {
                            additionalMessage = $";\r\n Diff: { patch.ToString()}";
                        }
                        // patch == null <--> jobjects match (except for key order)
                        Assert.IsNull(patch, $"Decryption failed: {testFile}{additionalMessage}");
                    }
                    else
                    {
                        //
                        // compare the processed result with a predefined json because the reversion
                        // round trip test is impossible
                        //
                        foreach (JProperty entry in json["assertions"])
                        {
                            string jsonpath       = entry.Name;
                            var    expectedResult = entry.Value;
                            JToken testResult     = resultJobject.SelectToken(jsonpath);
                            if (expectedResult != null && expectedResult.ToString() == "{}")
                            {
                                expectedResult = null;
                            }
                            if ((expectedResult == null || !expectedResult.HasValues) && testResult == null)
                            {
                                continue;
                            }
                            else if (expectedResult == null && testResult != null)
                            {
                                Assert.AreEqual(expectedResult, testResult.ToString(), $"Path {jsonpath} in {testFile} returned value {testResult} where null was expected.");
                            }
                            else if (expectedResult != null && testResult == null)
                            {
                                Assert.AreEqual(expectedResult.ToString(), testResult, $"Path {jsonpath} in {testFile} returned null where {expectedResult} was expected.");
                            }
                            else
                            {
                                Assert.AreEqual(expectedResult.ToString(), testResult.ToString(), $"Path {jsonpath} in {testFile} didn't return the expected result {expectedResult} but instead {testResult}");
                            }
                        }
                    }
                }
            }
        }