Beispiel #1
0
        //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "true" })]
        //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "false" })]

        public int v7()
        {
            if (!(IsFactoryTextReader() || IsBinaryReader() || IsFactoryValidatingReader()))
            {
                return(TEST_SKIPPED);
            }

            string            fileName = GetTestFileName(EREADER_TYPE.GENERIC);
            bool              ci       = bool.Parse(CurVariation.Params[0].ToString());
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.CloseInput = ci;
            CError.WriteLine(ci);
            MyDict <string, object> options = new MyDict <string, object>();

            options.Add(ReaderFactory.HT_FILENAME, fileName);
            options.Add(ReaderFactory.HT_READERSETTINGS, settings);

            ReloadSource(options);

            DataReader.PositionOnElement("elem2");
            XmlReader r = DataReader.ReadSubtree();

            CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive");

            DataReader.Close();
            return(TEST_PASS);
        }
Beispiel #2
0
        public override XmlReader Create(MyDict <string, object> options)
        {
            string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
            string tcVar  = (string)options[ReaderFactory.HT_CURVAR];

            CError.Compare(tcDesc == "custominheritedreader", "Invalid testcase");

            Stream       stream   = (Stream)options[ReaderFactory.HT_STREAM];
            string       filename = (string)options[ReaderFactory.HT_FILENAME];
            string       fragment = (string)options[ReaderFactory.HT_FRAGMENT];
            StringReader sr       = (StringReader)options[ReaderFactory.HT_STRINGREADER];

            if (sr != null)
            {
                return(new CustomReader(sr, false));
            }

            if (stream != null)
            {
                return(new CustomReader(stream));
            }

            if (fragment != null)
            {
                return(new CustomReader(new StringReader(fragment), true));
            }

            if (filename != null)
            {
                return(new CustomReader(filename));
            }

            throw new
                  CTestFailedException("CustomReader not created");
        }
        public override XmlReader Create(MyDict<string, object> options)
        {
            string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
            string tcVar = (string)options[ReaderFactory.HT_CURVAR];

            CError.Compare(tcDesc == "custominheritedreader", "Invalid testcase");

            Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
            string filename = (string)options[ReaderFactory.HT_FILENAME];
            string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
            StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER];

            if (sr != null)
            {
                return new CustomReader(sr, false);
            }

            if (stream != null)
            {
                return new CustomReader(stream);
            }

            if (fragment != null)
            {
                return new CustomReader(new StringReader(fragment), true);
            }

            if (filename != null)
            {
                return new CustomReader(filename);
            }

            throw new
                CTestFailedException("CustomReader not created");
        }
Beispiel #4
0
        public override XmlReader Create(MyDict<string, object> options)
        {
            XmlReaderSettings settings = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
            if (settings == null)
                settings = new XmlReaderSettings();

            Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
            string filename = (string)options[ReaderFactory.HT_FILENAME];
            object readerType = options[ReaderFactory.HT_READERTYPE];
            string fragment = (string)options[ReaderFactory.HT_FRAGMENT];

            if (stream != null)
            {
                XmlReader reader = ReaderHelper.Create(stream, settings, filename);
                return reader;
            }

            if (fragment != null)
            {
                StringReader tr = new StringReader(fragment);
                XmlReader reader = ReaderHelper.Create(tr, settings, "someUri");

                return reader;
            }

            if (filename != null)
            {
                XmlReader reader = ReaderHelper.Create(filename, settings);
                return reader;
            }

            throw new CTestFailedException("No Reader Created");
        }
Beispiel #5
0
        public override XmlReader Create(MyDict<string, object> options)
        {
            string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
            string tcVar = (string)options[ReaderFactory.HT_CURVAR];

            CError.Compare(tcDesc == "wrappedreader", "Invalid testcase");

            XmlReaderSettings rs = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
            Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
            string filename = (string)options[ReaderFactory.HT_FILENAME];
            object readerType = options[ReaderFactory.HT_READERTYPE];
            object vt = options[ReaderFactory.HT_VALIDATIONTYPE];
            string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
            StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER];

            if (rs == null)
                rs = new XmlReaderSettings();

            rs.DtdProcessing = DtdProcessing.Ignore;
            if (sr != null)
            {
                CError.WriteLine("WrappedReader String");

                XmlReader r = ReaderHelper.Create(sr, rs, string.Empty);
                XmlReader wr = ReaderHelper.Create(r, rs);
                return wr;
            }

            if (stream != null)
            {
                CError.WriteLine("WrappedReader Stream");

                XmlReader r = ReaderHelper.Create(stream, rs, filename);
                XmlReader wr = ReaderHelper.Create(r, rs);
                return wr;
            }

            if (fragment != null)
            {
                CError.WriteLine("WrappedReader Fragment");
                rs.ConformanceLevel = ConformanceLevel.Fragment;
                StringReader tr = new StringReader(fragment);

                XmlReader r = ReaderHelper.Create(tr, rs, (string)null);
                XmlReader wr = ReaderHelper.Create(r, rs);
                return wr;
            }

            if (filename != null)
            {
                CError.WriteLine("WrappedReader Filename");

                Stream fs = FilePathUtil.getStream(filename);
                XmlReader r = ReaderHelper.Create(fs, rs, filename);
                XmlReader wr = ReaderHelper.Create(r, rs);
                return wr;
            }
            throw new CTestFailedException("WrappedReader not created");
        }
Beispiel #6
0
        public void Test()
        {
            MyList <int> l1 = new MyList2 <int>();
            MyList <int> l2 = new MyDict <int, float>();

            // Compilerfehler
            //MyList<int> l3 = new MyList<float>();
        }
Beispiel #7
0
        public void Test()
        {
            MyList l1 = new MyList <int>();
            MyList l2 = new MyDict <int, float>();

            object o1 = new MyList <int>();
            object o2 = new MyDict <int, float>();
        }
            public void RecursionTest1()
            {
                var mydict = new MyDict <string, int>();

                var result = mydict.ContainsKey("foo");

                Assert.IsFalse(result);
            }
Beispiel #9
0
 public virtual void ReloadSource(MyDict<string, object> options)
 {
     CloseReader();
     options[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant();
     options[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant();
     DataReader.Internal = TestModule.ReaderFactory.Create(options);
     PostReloadSource();
 }
Beispiel #10
0
        public static ProgState createProgState(IntStatement state)
        {
            MyIntStack <IntStatement> stack = new MyStack <IntStatement>();
            MyIntDict <String, int>   dict  = new MyDict <String, int>();
            MyIntList <int>           list  = new MyList <int>();
            IntFileTable filetable          = new FileTable();

            return(new ProgState(stack, dict, list, filetable, state));
        }
Beispiel #11
0
        public override XmlReader Create(MyDict <string, object> options)
        {
            string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
            string tcVar  = (string)options[ReaderFactory.HT_CURVAR];

            CError.Compare(tcDesc == "factoryreader", "Invalid testcase");

            XmlReaderSettings rs         = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
            Stream            stream     = (Stream)options[ReaderFactory.HT_STREAM];
            string            filename   = (string)options[ReaderFactory.HT_FILENAME];
            object            readerType = options[ReaderFactory.HT_READERTYPE];
            object            vt         = options[ReaderFactory.HT_VALIDATIONTYPE];
            string            fragment   = (string)options[ReaderFactory.HT_FRAGMENT];
            StringReader      sr         = (StringReader)options[ReaderFactory.HT_STRINGREADER];

            if (rs == null)
            {
                rs = new XmlReaderSettings();
            }

            rs.DtdProcessing = DtdProcessing.Ignore;

            if (sr != null)
            {
                CError.WriteLine("StringReader");
                XmlReader reader = ReaderHelper.Create(sr, rs, string.Empty);
                return(reader);
            }

            if (stream != null)
            {
                CError.WriteLine("Stream");
                XmlReader reader = ReaderHelper.Create(stream, rs, filename);
                return(reader);
            }

            if (fragment != null)
            {
                CError.WriteLine("Fragment");
                rs.ConformanceLevel = ConformanceLevel.Fragment;
                StringReader tr     = new StringReader(fragment);
                XmlReader    reader = ReaderHelper.Create(tr, rs, (string)null);

                return(reader);
            }

            if (filename != null)
            {
                CError.WriteLine("Filename");
                XmlReader reader = ReaderHelper.Create(filename, rs);
                return(reader);
            }

            throw new
                  CTestFailedException("Factory Reader not created");
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            MyDict <string, MyObj> dict;

            dict = new MyDict <string, MyObj>();
            MyObj sampleObj = new MyObj();

            dict.Add("aaa", sampleObj);
            MyObj xxx = dict["aaa"];
        }
Beispiel #13
0
    static void Main(string[] args)
    {
        MyDict <string, int> d = new MyDict <string, int>();

        d.Add("hello", 666);
        d.Add("A", 1);
        d.Add("B", 2);
        d.Add("C", 3);

        MyDictInfo <string, int>(d);
        Console.ReadKey();
    }
    public T Invoke(FastFunc <T, int> f, int bla)
    {
        if (cache == null)
        {
            cache = new MyDict <int, T> ();
        }

        T value = f.Invoke(bla);

        cache.Add(bla, value);

        return(value);
    }
Beispiel #15
0
        private static Controller createController(IStmt statement)
        {
            String              logPath       = "/Users/adrianflorea/Codes/MAP/A7/log.out";
            IStack <IStmt>      myStack1      = new MyStack <IStmt>();
            IDict <String, int> myDictionary1 = new MyDict <String, int>();
            IList <int>         myList1       = new MyList <int>();
            IDictRandIntKey <MyTuple <String, TextReader> > myFileTable = new FileTable <MyTuple <String, TextReader> >();
            PrgState    state = new PrgState(myStack1, myDictionary1, myList1, myFileTable, statement);
            IRepository repo  = new Repo(state, logPath);
            Controller  ctrl  = new Controller(repo);

            return(ctrl);
        }
Beispiel #16
0
        static void initXmlFileCacheIfNotYet()
        {
            if (null == s_XmlFileInMemoryCache)
            {
                s_XmlFileInMemoryCache       = new MyDict <string, Stream>();
                s_XmlFileInMemoryCacheBackup = new MyDict <string, Stream>();

                foreach (var file in GetDataFiles())
                {
                    addBytes(file.Item1, file.Item2);
                }
            }
        }
Beispiel #17
0
 static void MyDictInfo <K, V>(MyDict <K, V> d)
 {
     Console.WriteLine("-------------");
     Console.WriteLine(d.Count);
     for (int i = 0; i < d.capcity; ++i)
     {
         if (d.mem[i] == null)
         {
             continue;
         }
         Console.Write(d.mem[i]);
         Console.Write(" ");
     }
     Console.WriteLine("=============");
 }
Beispiel #18
0
        public void TestMyDict()
        {
            var dict = new MyDict();

            dict["A"] = "A";
            dict["B"] = "B";

            var a = new
            {
                DICT = dict,
            };
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(a);

            json = EasyJsonSerializer.Serialize(a);
            json = Jil.JSON.Serialize(a);
        }
Beispiel #19
0
        static void initXmlFileCacheIfNotYet()
        {
            lock (s_XmlFileMemoryCacheLock)
            {
                if (s_XmlFileInMemoryCache == null)
                {
                    MyDict <string, MemoryStream> cache = new MyDict <string, MemoryStream>();

                    foreach (Tuple <string, byte[]> file in GetDataFiles())
                    {
                        var ms = new MemoryStream(file.Item2);
                        cache[NormalizeFilePath(file.Item1)] = ms;
                    }

                    s_XmlFileInMemoryCache = cache;
                }
            }
        }
Beispiel #20
0
        public int TestReadValueOnPIs0()
        {
            if (!IsFactoryReader())
            {
                return(TEST_SKIPPED);
            }

            char[] buffer = null;

            buffer = new char[3];

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreProcessingInstructions = true;

            MyDict <string, object> ht = new MyDict <string, object>();

            ht[ReaderFactory.HT_CURDESC]        = GetDescription().ToLowerInvariant();
            ht[ReaderFactory.HT_CURVAR]         = CurVariation.Desc.ToLowerInvariant();
            ht[ReaderFactory.HT_STRINGREADER]   = new StringReader("<root>val<?pi target?>ue</root>");
            ht[ReaderFactory.HT_READERSETTINGS] = settings;

            ReloadSource(ht);
            DataReader.PositionOnElement("root");
            DataReader.Read(); //This takes to text node.

            CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didn't read 3 chars");
            CError.Compare("val", new string(buffer), "Strings don't match");

            buffer = new char[2];
            DataReader.Read(); //This takes to text node.
            CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didn't read 2 chars");
            CError.Compare("ue", new string(buffer), "Strings don't match");

            while (DataReader.Read())
            {
                ;
            }
            DataReader.Close();

            return(TEST_PASS);
        }
    public static int Main()
    {
        StringFastFunc          sff = new StringFastFunc();
        ArrayFastFunc           aff = new ArrayFastFunc();
        IntCache <string>       ics = new IntCache <string> ();
        MyDict <string, string> dss = new MyDict <string, string> ();

        dss.Add("123", "456");

        ics.Invoke(sff, 123);
        ics.Invoke(sff, 456);

        IntCache <byte []> ica = new IntCache <byte []> ();

        ica.Invoke(aff, 1);
        ica.Invoke(aff, 2);
        ica.Invoke(aff, 3);

        return(0);
    }
Beispiel #22
0
        private void ProcessIncludes(string[] parentFilters, string defaultSection, XElement testModuleNode, MyDict <string, object> masterList, IList xmlDriverParams)
        {
            // loop through all includes cases
            foreach (XElement includeNode in testModuleNode.Elements("Include"))
            {
                string includeName           = SelectExistingAttributeValue(includeNode, "Name");
                string includeControlFile    = SelectExistingValue(includeNode, "ControlFile");
                string includeDefaultSection = SelectValue(includeNode, "DefaultSection", defaultSection);
                if (masterList != null && masterList[includeControlFile] != null)
                {
                    throw new CXmlDriverException("Reference cycle is detected in the control file " + includeControlFile);
                }

                IEnumerable <XElement> includeFilterNodes = includeNode.Elements("Filter");

                // add filters from <INCLUDE> section
                string[] includeFilters = null;
                int      count          = Enumerable.Count(includeFilterNodes);
                if (count > 0)
                {
                    string[]   tmp  = new string[count];
                    XElement[] list = Enumerable.ToArray(includeFilterNodes);
                    for (int i = 0; i < count; i++)
                    {
                        tmp[i] = list[i].Value;
                    }
                    includeFilters = (string[])CombineArrays(parentFilters, tmp);
                }
                else
                {
                    includeFilters = parentFilters;
                }

                MyDict <string, object> newMasterList = masterList == null ? new MyDict <string, object>() : masterList;
                newMasterList[includeControlFile] = true;

                ParseControlFile(includeName, includeControlFile, includeFilters, includeDefaultSection, includeNode, masterList, xmlDriverParams);
            }
        }
 public abstract XmlReader Create(MyDict<string, object> options);
Beispiel #24
0
        static void initXmlFileCacheIfNotYet()
        {
            if (null == s_XmlFileInMemoryCache)
            {
                s_XmlFileInMemoryCache = new MyDict<string, Stream>();
                s_XmlFileInMemoryCacheBackup = new MyDict<string, Stream>();

                foreach (var file in GetDataFiles())
                {
                    addBytes(file.Item1, file.Item2);
                }
            }
        }
Beispiel #25
0
 public abstract XmlReader Create(MyDict <string, object> options);
Beispiel #26
0
        public bool CompareStringWithPrefixes(string strExpected)
        {
            MyDict <string, object> AutoIDs   = new MyDict <string, object>();
            List <string>           AttNames  = new List <string>();
            List <string>           AttScopes = new List <string>();

            string strActual = this.GetString();

            int expLen = (strExpected == null ? 0 : strExpected.Length);
            int actLen = (strActual == null ? 0 : strActual.Length);

            int minLen = (expLen < actLen ? expLen : actLen);

            // find the first different character
            int i, j = 0;

            for (i = 0; i < actLen; i++)
            {
                if (j >= expLen)
                {
                    CError.WriteLine("Output longer than expected!");
                    CError.WriteLine("Actual string: '" + strActual + "'");
                    return(false);
                }

                if (strExpected[j] != strActual[i])
                {
                    if (strExpected[j] != PREFIX_CHAR)
                    {
                        CError.WriteLine("Position:" + i);
                        CError.WriteLine("Expected char:'" + strExpected[i] + "'(" + Convert.ToInt32(strExpected[i]) + ")");
                        CError.WriteLine("Actual char:'" + strActual[i] + "'(" + Convert.ToInt32(strActual[i]) + ")");
                        return(false);
                    }

                    bool AutoGenerated = strExpected[++j] == AUTOGENERATED;
                    j += 2;
                    string ActName = "";
                    string ExpName = "";
                    string Scope   = "";
                    while (i <= actLen)
                    {
                        if (strActual[i] == '=' || strActual[i] == ' ' || strActual[i] == ':')
                        {
                            i--;
                            break;
                        }
                        else
                        {
                            ActName += strActual[i];
                        }
                        i++;
                    }
                    while (strExpected[j] != ' ')
                    {
                        ExpName += strExpected[j++];
                    }
                    j++;
                    while (strExpected[j] != PREFIX_CHAR)
                    {
                        Scope += strExpected[j++];
                    }

                    if (AutoGenerated)
                    {
                        if (AutoIDs.ContainsKey(ExpName))
                        {
                            if ((string)AutoIDs[ExpName] != ActName)
                            {
                                CError.WriteLine("Invalid Prefix: '" + ActName + "'");
                                return(false);
                            }
                        }
                        else
                        {
                            AutoIDs.Add(ExpName, ActName);
                        }
                    }
                    else
                    {
                        if (ExpName != ActName)
                        {
                            CError.WriteLine("Invalid Prefix: '" + ActName + "'");
                            return(false);
                        }
                    }

                    for (int k = 0; k < AttNames.Count; k++)
                    {
                        if ((string)AttNames[k] == ActName)
                        {
                            for (int m = 0; m < ((string)AttScopes[k]).Length; m++)
                            {
                                for (int n = 0; n < Scope.Length; n++)
                                {
                                    if (((string)AttScopes[k])[m] == Scope[n])
                                    {
                                        CError.WriteLine("Invalid Prefix: '" + ActName + "'");
                                        return(false);
                                    }
                                }
                            }
                        }
                    }
                    AttNames.Add(ActName);
                    AttScopes.Add(Scope);
                }
                j++;
            }
            if (j != expLen)
            {
                CError.WriteLine("Output shorter than expected!");
                CError.WriteLine("Actual string: '" + strActual + "'");
                return(false);
            }

            return(true);
        }
Beispiel #27
0
        static public MyDict<string, string> ParseKeywords(string str, Tokens tokens)
        {
            PARSE state = PARSE.Initial;
            int index = 0;
            int keyStart = 0;
            MyDict<string, string> keywords = new MyDict<string, string>();
            string key = null;

            if (str != null)
            {
                StringBuilder builder = new StringBuilder(str.Length);
                for (; index < str.Length; index++)
                {
                    char ch = str[index];
                    switch (state)
                    {
                        case PARSE.Initial:
                            if (Char.IsLetterOrDigit(ch))
                            {
                                keyStart = index;
                                state = PARSE.Keyword;
                            }
                            break;

                        case PARSE.Keyword:
                            if (tokens.Equal.IndexOf(ch) >= 0)
                            {
                                //Note: We have a case-insentive hashtable so we don't have to lowercase
                                key = str.Substring(keyStart, index - keyStart).Trim();
                                state = PARSE.Equal;
                            }
                            break;

                        case PARSE.Equal:
                            if (Char.IsWhiteSpace(ch))
                                break;
                            builder.Length = 0;

                            //Note: Since we allow you to alter the tokens, these are not 
                            //constant values, so we cannot use a switch statement...
                            if (tokens.SingleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.SingleBegin;
                            }
                            else if (tokens.DoubleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.DoubleBegin;
                            }
                            else if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                keywords[key] = String.Empty;
                                state = PARSE.Initial;
                            }
                            else
                            {
                                state = PARSE.Value;
                                builder.Append(ch);
                            }
                            break;

                        case PARSE.Value:
                            if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                keywords[key] = (builder.ToString()).Trim();
                                state = PARSE.Initial;
                            }
                            else
                            {
                                builder.Append(ch);
                            }
                            break;

                        case PARSE.SingleBegin:
                            if (tokens.SingleQuote.IndexOf(ch) >= 0)
                                state = PARSE.SingleEnd;
                            else
                                builder.Append(ch);
                            break;

                        case PARSE.DoubleBegin:
                            if (tokens.DoubleQuote.IndexOf(ch) >= 0)
                                state = PARSE.DoubleEnd;
                            else
                                builder.Append(ch);
                            break;

                        case PARSE.SingleEnd:
                            if (tokens.SingleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.SingleBegin;
                                builder.Append(ch);
                            }
                            else
                            {
                                keywords[key] = builder.ToString();
                                state = PARSE.End;
                                goto case PARSE.End;
                            }
                            break;

                        case PARSE.DoubleEnd:
                            if (tokens.DoubleQuote.IndexOf(ch) >= 0)
                            {
                                state = PARSE.DoubleBegin;
                                builder.Append(ch);
                            }
                            else
                            {
                                keywords[key] = builder.ToString();
                                state = PARSE.End;
                                goto case PARSE.End;
                            }
                            break;

                        case PARSE.End:
                            if (tokens.Seperator.IndexOf(ch) >= 0)
                            {
                                state = PARSE.Initial;
                            }
                            break;

                        default:
                            Common.Assert(false, "Unhandled State " + Common.ToString(state));
                            break;
                    }
                }

                switch (state)
                {
                    case PARSE.Initial:
                    case PARSE.Keyword:
                    case PARSE.End:
                        break;

                    case PARSE.Equal:
                        keywords[key] = String.Empty;
                        break;

                    case PARSE.Value:
                        keywords[key] = (builder.ToString()).Trim();
                        break;

                    case PARSE.SingleBegin:
                    case PARSE.DoubleBegin:
                    case PARSE.SingleEnd:
                    case PARSE.DoubleEnd:
                        keywords[key] = builder.ToString();
                        break;

                    default:
                        Common.Assert(false, "Unhandled State " + Common.ToString(state));
                        break;
                };
            }
            return keywords;
        }
Beispiel #28
0
        private void ParseControlFile(string testCaseNamePrefix, string controlFile, string[] filters, string defaultSection, XElement topNode, MyDict <string, object> masterList, IList xmlDriverParams)
        {
            // load the control file
            XDocument doc = LoadControlFile(controlFile);

            // parse test module top node
            XElement testModuleNode = doc.Element("TestModule");

            AddBuiltInAttributes(testModuleNode);
            XElement testModuleVirtualNode = (topNode == null) ? testModuleNode :
                                             BuildVirtualNode(new XElement(topNode), testModuleNode);
            string testModuleName        = SelectExistingAttributeValue(testModuleNode, "Name");
            string testModuleCreated     = SelectExistingAttributeValue(testModuleNode, "Created");
            string testModuleModified    = SelectExistingAttributeValue(testModuleNode, "Modified");
            string testModuleDescription = SelectDescription(testModuleNode);

            CXmlDriverParamRawNodes testModuleParam = new CXmlDriverParamRawNodes_TestModule(testModuleNode, testModuleVirtualNode, null);

            xmlDriverParams.Add(new CXmlDriverParam(testModuleParam, defaultSection));

            // process includes
            ProcessIncludes(filters, defaultSection, testModuleNode, masterList, xmlDriverParams);

            // filter xPath
            string filterXPath = CombineXPath(filters);

            // loop through all test cases
            foreach (XElement testCaseNode in testModuleNode.Elements("TestCase"))
            {
                string testCaseName = SelectExistingAttributeValue(testCaseNode, "Name");
                if (testCaseNamePrefix != null && testCaseNamePrefix != "")
                {
                    testCaseName = testCaseNamePrefix + "_" + testCaseName;
                }
                string testCaseDescription = SelectDescription(testCaseNode);

                XElement testCaseVirtualNode          = null;
                CXmlDriverParamRawNodes testCaseParam = new CXmlDriverParamRawNodes_TestCase(testCaseNode, testCaseVirtualNode, testModuleParam);

                // create a test case class
                CTestCase testCase = CreateTestCase(testCaseName, testCaseDescription, new CXmlDriverParam(testCaseParam, defaultSection));

                // loop through all variations
                int varCount    = 0;
                int actVarCount = 0;
                foreach (XElement varNode in testCaseNode.Elements("Variation"))
                {
                    varCount++;
                    string   varId          = SelectExistingAttributeValue(varNode, "Id");
                    string   varName        = SelectName(varNode);
                    string   varPri         = SelectPriority(varNode);
                    XElement varVirtualNode = null;

                    // check filter
                    CXmlDriverParamRawNodes varParam = new CXmlDriverParamRawNodes_Variation(varNode, varVirtualNode, testCaseParam);
                    if (!CheckFilter(varParam, filterXPath))
                    {
                        continue;
                    }

                    // create a new variation and add it to the current testCase
                    actVarCount++;
                    string varDescription   = SelectDescription(varNode);
                    CXmlDriverVariation var = new CXmlDriverVariation((CXmlDriverScenario)testCase,
                                                                      varName, varDescription, Int32.Parse(varId), Int32.Parse(varPri),
                                                                      new CXmlDriverParam(varParam, defaultSection));
                    testCase.AddVariation(var);
                }

                if (actVarCount == 0 && varCount > 0)
                {
                    // no 'implemented' variations satisfying the filter
                    testCase = new CXmlDriverEmptyTestCase(testCaseName, testCaseDescription,
                                                           " no variations with @Implemented='True' " +
                                                           (_requiredLanguage != null && _requiredLanguage.Length != 0 ? " and @Language='" + _requiredLanguage + "'" : "") +
                                                           (filterXPath == null ? "" : " and satisfying '" + filterXPath + "'"), _testModule);
                }

                // add test case
                _testModule.AddTestCase(testCase);
            }
        }
Beispiel #29
0
        public virtual void ReloadSource(string filename)
        {
            MyDict<string, object> ht = new MyDict<string, object>();
            ht[ReaderFactory.HT_FILENAME] = filename;

            ReloadSource(ht);
        }
Beispiel #30
0
        public bool CompareStringWithPrefixes(string strExpected)
        {
            MyDict<string, object> AutoIDs = new MyDict<string, object>();
            List<string> AttNames = new List<string>();
            List<string> AttScopes = new List<string>();

            string strActual = this.GetString();

            int expLen = (strExpected == null ? 0 : strExpected.Length);
            int actLen = (strActual == null ? 0 : strActual.Length);

            int minLen = (expLen < actLen ? expLen : actLen);

            // find the first different character
            int i, j = 0;
            for (i = 0; i < actLen; i++)
            {
                if (j >= expLen)
                {
                    CError.WriteLine("Output longer than expected!");
                    CError.WriteLine("Actual string: '" + strActual + "'");
                    return false;
                }

                if (strExpected[j] != strActual[i])
                {
                    if (strExpected[j] != PREFIX_CHAR)
                    {
                        CError.WriteLine("Position:" + i);
                        CError.WriteLine("Expected char:'" + strExpected[i] + "'(" + Convert.ToInt32(strExpected[i]) + ")");
                        CError.WriteLine("Actual char:'" + strActual[i] + "'(" + Convert.ToInt32(strActual[i]) + ")");
                        return false;
                    }

                    bool AutoGenerated = strExpected[++j] == AUTOGENERATED;
                    j += 2;
                    string ActName = "";
                    string ExpName = "";
                    string Scope = "";
                    while (i <= actLen)
                    {
                        if (strActual[i] == '=' || strActual[i] == ' ' || strActual[i] == ':')
                        {
                            i--;
                            break;
                        }
                        else
                        {
                            ActName += strActual[i];
                        }
                        i++;
                    }
                    while (strExpected[j] != ' ')
                    {
                        ExpName += strExpected[j++];
                    }
                    j++;
                    while (strExpected[j] != PREFIX_CHAR)
                    {
                        Scope += strExpected[j++];
                    }

                    if (AutoGenerated)
                    {
                        if (AutoIDs.ContainsKey(ExpName))
                        {
                            if ((string)AutoIDs[ExpName] != ActName)
                            {
                                CError.WriteLine("Invalid Prefix: '" + ActName + "'");
                                return false;
                            }
                        }
                        else
                        {
                            AutoIDs.Add(ExpName, ActName);
                        }
                    }
                    else
                    {
                        if (ExpName != ActName)
                        {
                            CError.WriteLine("Invalid Prefix: '" + ActName + "'");
                            return false;
                        }
                    }

                    for (int k = 0; k < AttNames.Count; k++)
                    {
                        if ((string)AttNames[k] == ActName)
                        {
                            for (int m = 0; m < ((string)AttScopes[k]).Length; m++)
                                for (int n = 0; n < Scope.Length; n++)
                                    if (((string)AttScopes[k])[m] == Scope[n])
                                    {
                                        CError.WriteLine("Invalid Prefix: '" + ActName + "'");
                                        return false;
                                    }
                        }
                    }
                    AttNames.Add(ActName);
                    AttScopes.Add(Scope);
                }
                j++;
            }
            if (j != expLen)
            {
                CError.WriteLine("Output shorter than expected!");
                CError.WriteLine("Actual string: '" + strActual + "'");
                return false;
            }

            return true;
        }
Beispiel #31
0
 public virtual void ReloadSourceStr(string strxml)
 {
     MyDict<string, object> ht = new MyDict<string, object>();
     ht[ReaderFactory.HT_FRAGMENT] = strxml;
     ReloadSource(ht);
 }
Beispiel #32
0
        private void ProcessIncludes(string[] parentFilters, string defaultSection, XElement testModuleNode, MyDict<string, object> masterList, IList xmlDriverParams)
        {
            // loop through all includes cases
            foreach (XElement includeNode in testModuleNode.Elements("Include"))
            {
                string includeName = SelectExistingAttributeValue(includeNode, "Name");
                string includeControlFile = SelectExistingValue(includeNode, "ControlFile");
                string includeDefaultSection = SelectValue(includeNode, "DefaultSection", defaultSection);
                if (masterList != null && masterList[includeControlFile] != null)
                    throw new CXmlDriverException("Reference cycle is detected in the control file " + includeControlFile);

                IEnumerable<XElement> includeFilterNodes = includeNode.Elements("Filter");

                // add filters from <INCLUDE> section
                string[] includeFilters = null;
                int count = Enumerable.Count(includeFilterNodes);
                if (count > 0)
                {
                    string[] tmp = new string[count];
                    XElement[] list = Enumerable.ToArray(includeFilterNodes);
                    for (int i = 0; i < count; i++)
                        tmp[i] = list[i].Value;
                    includeFilters = (string[])CombineArrays(parentFilters, tmp);
                }
                else
                    includeFilters = parentFilters;

                MyDict<string, object> newMasterList = masterList == null ? new MyDict<string, object>() : masterList;
                newMasterList[includeControlFile] = true;

                ParseControlFile(includeName, includeControlFile, includeFilters, includeDefaultSection, includeNode, masterList, xmlDriverParams);
            }
        }
Beispiel #33
0
        //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "true" })]
        //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "false" })]

        public int v7()
        {
            if (!(IsFactoryTextReader() || IsBinaryReader() || IsFactoryValidatingReader()))
            {
                return TEST_SKIPPED;
            }

            string fileName = GetTestFileName(EREADER_TYPE.GENERIC);
            bool ci = Boolean.Parse(CurVariation.Params[0].ToString());
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = ci;
            CError.WriteLine(ci);
            MyDict<string, object> options = new MyDict<string, object>();
            options.Add(ReaderFactory.HT_FILENAME, fileName);
            options.Add(ReaderFactory.HT_READERSETTINGS, settings);

            ReloadSource(options);

            DataReader.PositionOnElement("elem2");
            XmlReader r = DataReader.ReadSubtree();

            CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive");

            DataReader.Close();
            return TEST_PASS;
        }
Beispiel #34
0
 private void ParseControlFileSafe(string testCaseNamePrefix, string controlFile, string[] filters, string defaultSection, XElement topNode, MyDict<string, object> masterList, IList xmlDriverParams)
 {
     try
     {
         _parseError = null;
         ParseControlFile(testCaseNamePrefix, controlFile, filters, defaultSection, topNode, masterList, xmlDriverParams);
     }
     catch (Exception e)
     {
         HandleException(e);
     }
 }
Beispiel #35
0
        private void ParseControlFile(string testCaseNamePrefix, string controlFile, string[] filters, string defaultSection, XElement topNode, MyDict<string, object> masterList, IList xmlDriverParams)
        {
            // load the control file
            XDocument doc = LoadControlFile(controlFile);

            // parse test module top node
            XElement testModuleNode = doc.Element("TestModule");
            AddBuiltInAttributes(testModuleNode);
            XElement testModuleVirtualNode = (topNode == null) ? testModuleNode :
                BuildVirtualNode(new XElement(topNode), testModuleNode);
            string testModuleName = SelectExistingAttributeValue(testModuleNode, "Name");
            string testModuleCreated = SelectExistingAttributeValue(testModuleNode, "Created");
            string testModuleModified = SelectExistingAttributeValue(testModuleNode, "Modified");
            string testModuleDescription = SelectDescription(testModuleNode);

            CXmlDriverParamRawNodes testModuleParam = new CXmlDriverParamRawNodes_TestModule(testModuleNode, testModuleVirtualNode, null);
            xmlDriverParams.Add(new CXmlDriverParam(testModuleParam, defaultSection));

            // process includes
            ProcessIncludes(filters, defaultSection, testModuleNode, masterList, xmlDriverParams);

            // filter xPath 
            string filterXPath = CombineXPath(filters);

            // loop through all test cases
            foreach (XElement testCaseNode in testModuleNode.Elements("TestCase"))
            {
                string testCaseName = SelectExistingAttributeValue(testCaseNode, "Name");
                if (testCaseNamePrefix != null && testCaseNamePrefix != "")
                    testCaseName = testCaseNamePrefix + "_" + testCaseName;
                string testCaseDescription = SelectDescription(testCaseNode);

                XElement testCaseVirtualNode = null;
                CXmlDriverParamRawNodes testCaseParam = new CXmlDriverParamRawNodes_TestCase(testCaseNode, testCaseVirtualNode, testModuleParam);

                // create a test case class
                CTestCase testCase = CreateTestCase(testCaseName, testCaseDescription, new CXmlDriverParam(testCaseParam, defaultSection));

                // loop through all variations
                int varCount = 0;
                int actVarCount = 0;
                foreach (XElement varNode in testCaseNode.Elements("Variation"))
                {
                    varCount++;
                    string varId = SelectExistingAttributeValue(varNode, "Id");
                    string varName = SelectName(varNode);
                    string varPri = SelectPriority(varNode);
                    XElement varVirtualNode = null;

                    // check filter
                    CXmlDriverParamRawNodes varParam = new CXmlDriverParamRawNodes_Variation(varNode, varVirtualNode, testCaseParam);
                    if (!CheckFilter(varParam, filterXPath))
                        continue;

                    // create a new variation and add it to the current testCase 
                    actVarCount++;
                    string varDescription = SelectDescription(varNode);
                    CXmlDriverVariation var = new CXmlDriverVariation((CXmlDriverScenario)testCase,
                        varName, varDescription, Int32.Parse(varId), Int32.Parse(varPri),
                        new CXmlDriverParam(varParam, defaultSection));
                    testCase.AddVariation(var);
                }

                if (actVarCount == 0 && varCount > 0)
                    // no 'implemented' variations satisfying the filter
                    testCase = new CXmlDriverEmptyTestCase(testCaseName, testCaseDescription,
                        " no variations with @Implemented='True' " +
                        (_requiredLanguage != null && _requiredLanguage.Length != 0 ? " and @Language='" + _requiredLanguage + "'" : "") +
                        (filterXPath == null ? "" : " and satisfying '" + filterXPath + "'"), _testModule);

                // add test case
                _testModule.AddTestCase(testCase);
            }
        }
 public virtual void ReloadSource(MyDict<string, object> options);
Beispiel #37
0
        static void Main(string[] args)
        {
            ImyStack <Istmt>      stk1 = new MyStack <Istmt>();
            ImyDict <string, int> s1   = new MyDict <string, int>();
            ImyList <int>         o1   = new MyList <int>();
            ImyDict <int, Tuple <string, StreamReader> > f1 = new MyTDict();

            /*
             * a = 2 - 2;
             * If a Then v = 2 Else v = 3;
             * Print(v)
             */

            Istmt stmt1 =

                new Compound(
                    new Assign("a", new Arith(new Const(2), new Const(2), 1)),
                    new Compound(
                        new If(new Var("a"), new Assign("v", new Const(2)), new Assign("v", new Const(3))),
                        new Print(new Var("v"))
                        )
                    );


            stk1.push(stmt1);
            PrgState state1 = new PrgState(stk1, s1, o1, f1);

            Ctrl ctr1 = new Ctrl(state1);

            ImyStack <Istmt>      stk2 = new MyStack <Istmt>();
            ImyDict <string, int> s2   = new MyDict <string, int>();
            ImyList <int>         o2   = new MyList <int>();
            ImyDict <int, Tuple <string, StreamReader> > f2 = new MyTDict();

            /*
             * a = 2 - 2;
             * If a Then v = 2 Else v = 3;
             * Print(v)
             */

            Istmt stmt2 =

                new Compound(
                    new OpenFile("a", "C:\\Users\\Radu\\documents\\visual studio 2015\\Projects\\MAP\\MAP\\test.txt"),
                    new Compound(
                        new Read(new Var("a"), "v"),
                        new Compound(
                            new Read(new Var("a"), "v"),
                            new Print(new Var("v"))
                            )
                        )
                    );


            stk2.push(stmt2);
            PrgState state2 = new PrgState(stk2, s2, o2, f2);

            Ctrl ctr2 = new Ctrl(state2);

            TextMenu menu = new TextMenu();

            menu.addCommand(new ExitCommand("0", "Exit"));
            menu.addCommand(new RunExample("1", stmt1.ToString(), ctr1));
            menu.addCommand(new RunExample("2", stmt2.ToString(), ctr2));

            try
            {
                menu.show();
            }
            catch (EndException)
            {
                return;
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
        }
Beispiel #38
0
 public virtual void ReloadSource(StringReader strRdr)
 {
     MyDict<string, object> ht = new MyDict<string, object>();
     ht[ReaderFactory.HT_STRINGREADER] = strRdr;
     ReloadSource(ht);
 }
Beispiel #39
0
 private void ParseControlFileSafe(string testCaseNamePrefix, string controlFile, string[] filters, string defaultSection, XElement topNode, MyDict <string, object> masterList, IList xmlDriverParams)
 {
     try
     {
         _parseError = null;
         ParseControlFile(testCaseNamePrefix, controlFile, filters, defaultSection, topNode, masterList, xmlDriverParams);
     }
     catch (Exception e)
     {
         HandleException(e);
     }
 }
Beispiel #40
0
        public int TestReadValueOnComments0()
        {
            if (!IsFactoryReader())
                return TEST_SKIPPED;

            char[] buffer = null;

            buffer = new char[3];

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;

            MyDict<string, object> ht = new MyDict<string, object>();
            ht[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant();
            ht[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant();
            ht[ReaderFactory.HT_STRINGREADER] = new StringReader("<root>val<!--Comment-->ue</root>");
            ht[ReaderFactory.HT_READERSETTINGS] = settings;

            ReloadSource(ht);
            DataReader.PositionOnElement("root");
            DataReader.Read(); //This takes to text node.

            CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didnt read 3 chars");
            CError.Compare("val", new string(buffer), "Strings dont match");

            buffer = new char[2];
            DataReader.Read(); //This takes to text node.
            CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didnt read 2 chars");
            CError.Compare("ue", new string(buffer), "Strings dont match");

            while (DataReader.Read()) ;
            DataReader.Close();

            return TEST_PASS;
        }
Beispiel #41
0
        public static void Main(string[] args)
        {
            IMyStack <IStatement>     stack1     = new MyStack <IStatement>();
            IMyDict <string, int>     dict1      = new MyDict <string, int>();
            IMyList <int>             output1    = new MyList <int>();
            FileTable <int, FileData> fileTable1 = new FileTable <int, FileData>();

            IStatement i1 = new OpenRFile("var_f", "../../../intrare.txt");
            IStatement i2 = new ReadFile(new VarExpression("var_f"), "var_c");
            IStatement i3 = new ReadFile(new VarExpression("var_f"), "var_c");
            IStatement i4 = new PrintStatement(new VarExpression("var_c"));
            IStatement i5 = new CompStatement(i3, i4);
            IStatement i6 = new PrintStatement(new ConstExpression(0));

            IStatement i7 = new IfStatement(new VarExpression("var_c"), i5, i6);
            IStatement i8 = new CloseRFile(new VarExpression("var_f"));

            IStatement i9  = new CompStatement(i1, i2);
            IStatement i10 = new CompStatement(i7, i8);
            IStatement i11 = new CompStatement(i9, i10);

            stack1.Push(i11);

            PrgState    state1 = new PrgState(dict1, stack1, output1, fileTable1);
            IRepository repo1  = new Repository.Repository();

            repo1.AddProg(state1);
            Controller.Controller ctrl1 = new Controller.Controller(repo1);

            /*Exemplu 111111111111111111111111111111111111111111111*/


            IMyStack <IStatement>     stack2     = new MyStack <IStatement>();
            IMyDict <string, int>     dict2      = new MyDict <string, int>();
            IMyList <int>             output2    = new MyList <int>();
            FileTable <int, FileData> fileTable2 = new FileTable <int, FileData>();

            IStatement j1 = new OpenRFile("a", "../../../intrare.txt");
            IStatement j2 = new CompStatement(new ReadFile(new VarExpression("a"), "p"), new PrintStatement(new VarExpression("p")));
            IStatement j3 = new IfStatement(new VarExpression("p"), new CompStatement(new ReadFile(new VarExpression("a"), "q"),
                                                                                      new PrintStatement(new VarExpression("q"))), new PrintStatement(new ConstExpression(0)));

            IStatement j4 = new CloseRFile(new VarExpression("a"));
            IStatement j5 = new CompStatement(j2, new CompStatement(j3, j4));
            IStatement j6 = new CompStatement(j1, j5);

            stack2.Push(j6);

            PrgState    state2 = new PrgState(dict2, stack2, output2, fileTable2);
            IRepository repo2  = new Repository.Repository();

            repo2.AddProg(state2);
            Controller.Controller ctrl2 = new Controller.Controller(repo2);
            /*Exemplu 222222222222222222222222222222222222222222222*/
            TextMenu menu = new TextMenu();

            menu.AddCommand(new ExitCommand("0", "exit \n"));
            menu.AddCommand(new RunCommand("1", "\t" + i11.ToString() + "\n", ctrl1));
            menu.AddCommand(new RunCommand("2", "\t" + j6.ToString() + "\n", ctrl2));
            menu.Show();
        }
Beispiel #42
0
        public override XmlReader Create(MyDict <string, object> options)
        {
            string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
            string tcVar  = (string)options[ReaderFactory.HT_CURVAR];

            CError.Compare(tcDesc == "charcheckingreader", "Invalid testcase");

            XmlReaderSettings rs         = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
            Stream            stream     = (Stream)options[ReaderFactory.HT_STREAM];
            string            filename   = (string)options[ReaderFactory.HT_FILENAME];
            object            readerType = options[ReaderFactory.HT_READERTYPE];
            object            vt         = options[ReaderFactory.HT_VALIDATIONTYPE];
            string            fragment   = (string)options[ReaderFactory.HT_FRAGMENT];
            StringReader      sr         = (StringReader)options[ReaderFactory.HT_STRINGREADER];

            if (rs == null)
            {
                rs = new XmlReaderSettings();
            }

            rs.DtdProcessing   = DtdProcessing.Ignore;
            rs.CheckCharacters = false;

            XmlReaderSettings wrs = new XmlReaderSettings();

            wrs.DtdProcessing    = DtdProcessing.Ignore;
            wrs.CheckCharacters  = true;
            wrs.ConformanceLevel = ConformanceLevel.Auto;

            if (sr != null)
            {
                CError.WriteLine("CharCheckingReader String");
                XmlReader r  = ReaderHelper.Create(sr, rs, string.Empty);
                XmlReader wr = ReaderHelper.Create(r, wrs);
                return(wr);
            }

            if (stream != null)
            {
                CError.WriteLine("CharCheckingReader Stream");
                XmlReader r  = ReaderHelper.Create(stream, rs, filename);
                XmlReader wr = ReaderHelper.Create(r, wrs);
                return(wr);
            }

            if (fragment != null)
            {
                CError.WriteLine("CharCheckingReader Fragment");
                rs.ConformanceLevel = ConformanceLevel.Fragment;
                StringReader tr = new StringReader(fragment);
                XmlReader    r  = ReaderHelper.Create(tr, rs, (string)null);
                XmlReader    wr = ReaderHelper.Create(r, wrs);
                return(wr);
            }

            if (filename != null)
            {
                CError.WriteLine("CharCheckingReader Filename");
                Stream    fs = FilePathUtil.getStream(filename);
                XmlReader r  = ReaderHelper.Create(fs, rs, filename);
                XmlReader wr = ReaderHelper.Create(r, wrs);
                return(wr);
            }
            return(null);
        }
Beispiel #43
0
        public static void Main()
        {
            #region Cleanup

            Db.SQL <RESTar.Dynamic.DynamicResource>("SELECT t FROM RESTar.Dynamic.DynamicResource t").ForEach(b => Db.TransactAsync(b.Delete));
            Db.SQL <Webhook>("SELECT t FROM RESTar.Admin.Webhook t").ForEach(b => Db.TransactAsync(b.Delete));
            Db.SQL <Base>("SELECT t FROM RESTarTester.Base t").ForEach(b => Db.TransactAsync(b.Delete));
            Db.SQL <MyDict>("SELECT t FROM RESTarTester.MyDict t").ForEach(b => Db.TransactAsync(b.Delete));
            Db.SQL <MyDict2>("SELECT t FROM RESTarTester.MyDict2 t").ForEach(b => Db.TransactAsync(b.Delete));

            #endregion

            #region Handles and Init()

            bool wrstreamcalled = false;
            bool wrbytescalled  = false;
            bool wrstringcalled = false;

            Handle.POST("/wrStream", (Request __r) =>
            {
                Debug.Assert(__r.BodyBytes.Length == 16);
                wrstreamcalled = true;
                return(HttpStatusCode.OK);
            });

            Handle.POST("/wrBytes", (Request __r) =>
            {
                Debug.Assert(__r.BodyBytes.Length == 23);
                wrbytescalled = true;
                return(HttpStatusCode.OK);
            });

            Handle.POST("/wrString", (Request __r) =>
            {
                Debug.Assert(__r.Body == "This is the very important message!");
                wrstringcalled = true;
                return(HttpStatusCode.OK);
            });

            RESTarConfig.Init
            (
                port: 9000,
                lineEndings: LineEndings.Windows,
                prettyPrint: true,
                allowAllOrigins: false,
                configFilePath: @"C:\Mopedo\mopedo\Mopedo.config"
            );

            #endregion

            #region Create resources and hooks

            using (var dynamicResourceRequest = Context.Root.CreateRequest <RESTar.Dynamic.Resource>(POST))
            {
                dynamicResourceRequest.Selector = () => new[]
                {
                    new RESTar.Dynamic.Resource {
                        Name = "wr1"
                    }, new RESTar.Dynamic.Resource {
                        Name = "wr2"
                    },
                    new RESTar.Dynamic.Resource {
                        Name = "wr3"
                    }, new RESTar.Dynamic.Resource {
                        Name = "wrResource1"
                    }
                };
                using (var drResult = dynamicResourceRequest.Evaluate())
                {
                    Debug.Assert(drResult is Change);
                }
            }

            using (var webhookRequest = Context.Root.CreateRequest <Webhook>(POST))
            {
                webhookRequest.Selector = () => new[]
                {
                    new Webhook {
                        Destination = "/wr1", EventSelector = $"/{typeof(ENotification).FullName}"
                    },
                    new Webhook {
                        Destination = "/wr2", EventSelector = $"/{typeof(ENotification).FullName}"
                    },
                    new Webhook {
                        Destination = "http://*****:*****@"{""Id"": 1, ""Str"": ""Foogoo""}"),
                                         headers: new Dictionary <string, string>()
            {
                ["password"] = "******"
            });
            var response5fail = Http.Request("POST", "http://*****:*****@"{""Id"": 2, ""Str"": ""Foogoo""}"),
                                             headers: new Dictionary <string, string>()
            {
                ["password"] = "******"
            });
            var response6 = Http.Request("POST", "http://localhost:9000/rest/resource1//safepost=ObjectNo", Encoding.UTF8.GetBytes(onesJson), null);

            Debug.Assert(response1?.IsSuccessStatusCode == true);
            Debug.Assert(response2?.IsSuccessStatusCode == true);
            Debug.Assert(response3?.IsSuccessStatusCode == true);
            Debug.Assert(response4?.IsSuccessStatusCode == true);
            Debug.Assert(response5?.IsSuccessStatusCode == true);
            Debug.Assert(response5fail?.StatusCode == (HttpStatusCode)403);
            Debug.Assert(response6?.IsSuccessStatusCode == true);

            #endregion

            var a = "";

            #region External source/destination inserts

            var resource1Url     = "https://storage.googleapis.com/mopedo-web/resource1.json";
            var esourceresponse1 = Http.Request
                                   (
                method: "POST",
                uri: "http://localhost:9000/rest/resource1",
                body: null,
                headers: new Dictionary <string, string> {
                ["Source"] = "GET " + resource1Url
            }
                                   );
            Debug.Assert(esourceresponse1?.IsSuccessStatusCode == true);

            var esourceresponse2 = Http.Request
                                   (
                method: "POST",
                uri: "http://localhost:9000/rest/MyDict",
                body: null,
                headers: new Dictionary <string, string> {
                ["Source"] = "GET " + resource1Url
            }
                                   );
            Debug.Assert(esourceresponse2?.IsSuccessStatusCode == true);

            var esourceresponse3 = Http.Request
                                   (
                method: "POST",
                uri: "http://localhost:9000/rest/MyDict",
                body: null,
                headers: new Dictionary <string, string> {
                ["Source"] = "GET /resource1"
            }
                                   );
            Debug.Assert(esourceresponse3?.IsSuccessStatusCode == true);

            var edestinationresponse1 = Http.Request
                                        (
                method: "GET",
                uri: "http://localhost:9000/rest/resource1",
                headers: new Dictionary <string, string> {
                ["Destination"] = "POST /mydict"
            }
                                        );
            Debug.Assert(edestinationresponse1?.IsSuccessStatusCode == true);

            var edestinationresponse2 = Http.Request
                                        (
                method: "GET",
                uri: "http://localhost:9000/rest/mydict",
                headers: new Dictionary <string, string> {
                ["Destination"] = "POST http://localhost:9000/rest/resource1"
            }
                                        );
            Debug.Assert(edestinationresponse2?.IsSuccessStatusCode == true);

            #endregion

            #region JSON GET

            var request = (HttpWebRequest)WebRequest.Create("http://localhost:9000/rest/resource1");
            request.Method = "GET";
            var response     = (HttpWebResponse)request.GetResponse();
            var rstream      = response.GetResponseStream();
            var streamreader = new StreamReader(rstream);
            var data         = streamreader.ReadToEnd();
            Debug.Assert(!string.IsNullOrWhiteSpace(data));

            var jsonResponse1         = Http.Request("GET", "http://localhost:9000/rest/restartester.resource1");
            var jsonResponse1view     = Http.Request("GET", "http://localhost:9000/rest/resource1-myview");
            var jsonResponse2         = Http.Request("GET", "http://localhost:9000/rest/resource2");
            var jsonResponse3         = Http.Request("GET", "http://localhost:9000/rest/resource3");
            var jsonResponse4         = Http.Request("GET", "http://localhost:9000/rest/resource4");
            var jsonResponse4distinct = Http.Request("GET", "http://localhost:9000/rest/resource4//select=string&distinct=true");
            var jsonResponse4extreme  = Http.Request("GET",
                                                     "http://localhost:9000/rest/resource4//add=datetime.day&select=datetime.day,datetime.month,string,string.length&order_desc=string.length&distinct=true");
            var jsonResponse5format = Http.Request("GET",
                                                   "http://localhost:9000/rest/resource4//add=datetime.day&select=datetime.day,datetime.month,string,string.length&order_desc=string.length&format=jsend&distinct=true");

            var head   = Http.Request("HEAD", "http://localhost:9000/rest/resource1//distinct=true");
            var report = Http.Request("REPORT", "http://localhost:9000/rest/resource1//distinct=true");

            Debug.Assert(jsonResponse1?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse1view?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse2?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse3?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse4?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse4distinct?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse4extreme?.IsSuccessStatusCode == true);
            Debug.Assert(jsonResponse5format?.IsSuccessStatusCode == true);

            #endregion

            #region GET Excel

            var headers = new Dictionary <string, string> {
                ["Accept"] = "application/restar-excel"
            };
            var excelResponse1 = Http.Request("GET", "http://localhost:9000/rest/resource1", headers: headers);
            var excelResponse2 = Http.Request("GET", "http://localhost:9000/rest/resource2", headers: headers);
            var excelResponse3 = Http.Request("GET", "http://localhost:9000/rest/resource3", headers: headers);
            var excelResponse4 = Http.Request("GET", "http://localhost:9000/rest/resource4", headers: headers);

            Debug.Assert(excelResponse1?.IsSuccessStatusCode == true);
            Debug.Assert(excelResponse2?.IsSuccessStatusCode == true);
            Debug.Assert(excelResponse3?.IsSuccessStatusCode == true);
            Debug.Assert(excelResponse4?.IsSuccessStatusCode == true);

            #endregion

            #region POST Excel

            var excelbody          = excelResponse1.Content.ReadAsByteArrayAsync().Result;
            var excelPostResponse1 = Http.Request("POST", "http://localhost:9000/rest/resource1", body: excelbody,
                                                  contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            Debug.Assert(excelPostResponse1?.IsSuccessStatusCode == true);

            var webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:9000/rest/resource1");
            webrequest.Method      = "POST";
            webrequest.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            using (var str = webrequest.GetRequestStream())
                using (var stream = new MemoryStream(excelbody))
                    stream.CopyTo(str);
            var    webResponse = (HttpWebResponse)webrequest.GetResponse();
            string _body;
            using (var reader = new StreamReader(webResponse.GetResponseStream()))
                _body = reader.ReadToEnd();
            Debug.Assert(webResponse.StatusCode < HttpStatusCode.BadRequest);

            #endregion

            #region With conditions

            var conditionResponse1 = Http.Request("GET", "http://localhost:9000/rest/resource1/sbyte>=0&byte!=200&datetime>2001-01-01");
            var conditionResponse2 = Http.Request("GET", "http://localhost:9000/rest/resource2/sbyte<=10&byte!=200&datetime>2001-01-01");
            var conditionResponse3 = Http.Request("GET", "http://localhost:9000/rest/resource3/sbyte>0&byte!=200&datetime>2001-01-01");
            var conditionResponse4 = Http.Request("GET", "http://localhost:9000/rest/resource4/resource1.string!=aboo&resource2!=null");

            Debug.Assert(excelResponse1?.IsSuccessStatusCode == true);
            Debug.Assert(excelResponse2?.IsSuccessStatusCode == true);
            Debug.Assert(excelResponse3?.IsSuccessStatusCode == true);
            Debug.Assert(excelResponse4?.IsSuccessStatusCode == true);

            #endregion

            #region Internal requests

            var context = Context.Root;
            var g       = context.CreateRequest <MyDict>(POST);
            g.Selector = () =>
            {
                dynamic d = new MyDict();
                d.Hej = "123";
                d.Foo = 3213M;
                d.Goo = true;
                dynamic v = new MyDict();
                v.Hej = "123";
                v.Foo = 3213M;
                v.Goo = false;
                dynamic x = new MyDict();
                x.Hej = "123";
                x.Foo = 3213M;
                x.Goo = false;
                return(new MyDict[] { d, v, x });
            };
            var result = g.Evaluate();
            Debug.Assert(result is InsertedEntities ie && ie.InsertedCount == 3);

            var     g2 = context.CreateRequest <MyDict>(POST);
            dynamic d2 = new JObject();
            d2.Hej = "123";
            d2.Foo = 3213M;
            d2.Goo = true;
            dynamic v2 = new JObject();
            v2.Hej = "123";
            v2.Foo = 3213M;
            v2.Goo = false;
            dynamic x2 = new JObject();
            x2.Hej = "123";
            x2.Foo = 3213M;
            x2.Goo = false;
            var arr2 = new[] { d2, v2, x2 };
            g2.SetBody(arr2);
            var result2 = g2.Evaluate();
            Debug.Assert(result2 is InsertedEntities ie2 && ie2.InsertedCount == 3);

            var     g5 = context.CreateRequest <MyDict>(POST);
            dynamic d5 = new JObject();
            d5.Hej = "123";
            d5.Foo = 3213M;
            d5.Goo = true;
            dynamic v5 = new JObject();
            v5.Hej = "123";
            v5.Foo = 3213M;
            v5.Goo = false;
            dynamic x5 = new JObject();
            x5.Hej = "123";
            x5.Foo = 3213M;
            x5.Goo = false;
            var arr5 = new[] { d5, v5, x5 };
            g5.SetBody(arr5, ContentType.Excel);
            var result5 = g5.Evaluate();
            Debug.Assert(result5 is InsertedEntities ie5 && ie5.InsertedCount == 3);

            var g3 = context.CreateRequest <MyDict>(POST);
            var d3 = new { Hej = "123", Foo = 3213M, Goo = true };
            g3.SetBody(d3);
            var result3 = g3.Evaluate();
            Debug.Assert(result3 is InsertedEntities ie3 && ie3.InsertedCount == 1);

            var g4 = context.CreateRequest <MyDict>(POST);
            var d4 = JsonConvert.SerializeObject(new { Hej = "123", Foo = 3213M, Goo = true });
            g4.SetBody(d4);
            var result4 = g4.Evaluate();
            Debug.Assert(result4 is InsertedEntities ie4 && ie4.InsertedCount == 1);


            var r1Cond = new Condition <Resource1>(nameof(Resource1.Sbyte), GREATER_THAN, 1);
            var r1     = context.CreateRequest <Resource1>(GET);
            r1.Conditions.Add(r1Cond);

            var r2 = context.CreateRequest <Resource2>(GET);
            var r3 = context.CreateRequest <Resource3>(GET);
            var r4 = context.CreateRequest <Resource4>(GET);
            var r6 = context.CreateRequest <Aggregator>(GET);
            r6.SetBody(new { A = "REPORT /admin.resource", B = new[] { "REPORT /admin.resource", "REPORT /admin.resource" } });
            var r5   = context.CreateRequest <Resource1>(GET);
            var cond = new Condition <Resource1>("SByte", GREATER_THAN, 2);
            r5.Conditions.Add(cond);
            r5.Headers.Accept = ContentType.Excel;

            var res1 = r1.Evaluate().Serialize();
            var res2 = r2.Evaluate().Serialize();
            var res3 = r3.Evaluate().Serialize();
            var res4 = r4.Evaluate().Serialize();
            var res5 = r5.Evaluate().Serialize();
            var res6 = r6.Evaluate().Serialize();

            Debug.Assert(res5.Headers.ContentType == ContentType.Excel);
            Debug.Assert(res5.Body.Length > 1);

            Db.TransactAsync(() =>
            {
                var x = new MyDict {
                    ["Hej"] = "123", ["Foo"] = 3213M, ["Goo"] = false
                };
                foreach (Resource1 asd in Db.SQL <Resource1>("SELECT t FROM RESTarTester.Resource1 t"))
                {
                    asd.MyDict = x;
                }
            });

            Do.Schedule(() => Db.TransactAsync(() => new MyDict()
            {
                ["Aaa"] = "Wook"
            }), TimeSpan.FromSeconds(10)).Wait();

            DatabaseIndex.Register <MyDict2>("MyFineIdex", "$R");

            Db.TransactAsync(() => { new MyDict2 {
                                         ["Snoo"] = 123, R = new Resource1 {
                                             Byte = 123, String = "Googfoo"
                                         }
                                     }; });

            var byInternalSource = Http.Request("POST", "http://localhost:9000/rest/resource3", null,
                                                headers: new Dictionary <string, string> {
                ["Source"] = "GET /resource3"
            });


            var internalRequest9 = Context.Root.CreateRequest <Resource1>();
            var entities9        = internalRequest9.EvaluateToEntities();
            Debug.Assert(entities9 is IEntities <Resource1> rement1 && rement1.Count() > 1 && entities9 is IEnumerable <Resource1>);

            var resource2Conditions = new Condition <Resource2>[]
            {
                new Condition <Resource2>(nameof(Resource2.Bool), EQUALS, false), new Condition <Resource2>(nameof(Resource2.Enum), EQUALS, MyEnum.D),
                new Condition <Resource2>(nameof(Resource2.BBool), EQUALS, false),
                new Condition <Resource2>(nameof(Resource2.Long), NOT_EQUALS, 42123),
            };
            var internalRequest10 = Context.Root
                                    .CreateRequest <Resource1>()
                                    .WithConditions(resource2Conditions.Redirect <Resource1>(
                                                        (direct: "BBool", to: "ABool"),
                                                        (direct: "Long", to: "Foobooasd")
                                                        ));
            var entities10 = internalRequest10.EvaluateToEntities();
            Debug.Assert(entities10 is IEntities <Resource1> _rement1 && _rement1.Count() > 1 && entities10 is IEnumerable <Resource1>);

            var c  = entities10.Count();
            var c2 = entities10.Count();

            var objectNo = entities10.FirstOrDefault().GetObjectNo();
            var objectId = entities10.Skip(1).FirstOrDefault().GetObjectID();

            var byObjectNo = Context.Root
                             .CreateRequest <Resource1>()
                             .WithConditions(new Condition <Resource1>("ObjectNo", EQUALS, objectNo))
                             .EvaluateToEntities()
                             .FirstOrDefault();

            var byObjectID = Context.Root
                             .CreateRequest <Resource1>()
                             .WithConditions(new Condition <Resource1>("ObjectID", EQUALS, objectId))
                             .EvaluateToEntities()
                             .FirstOrDefault();

            var byObjectIDThatDoesntExist = Context.Root
                                            .CreateRequest <Resource1>()
                                            .WithConditions(new Condition <Resource1>("ObjectID", EQUALS, new Stopwatch()))
                                            .EvaluateToEntities()
                                            .FirstOrDefault();

            Debug.Assert(byObjectNo is Resource1);
            Debug.Assert(byObjectID is Resource1);
            Debug.Assert(byObjectIDThatDoesntExist == null);

            #endregion

            #region Remote requests

            var remoteContext = Context.Remote("http://localhost:9000/rest");
            var remoteRequest = remoteContext.CreateRequest("/resource1", GET);
            var remoteResult  = remoteRequest.Evaluate();
            Debug.Assert(remoteResult is IEntities rement && rement.EntityCount > 1);

            #endregion

            #region OPTIONS

            var optionsResponse1 = Http.Request("OPTIONS", "http://localhost:9000/rest/resource1", null,
                                                headers: new Dictionary <string, string> {
                ["Origin"] = "https://fooboo.com/thingy"
            });
            Debug.Assert(optionsResponse1?.IsSuccessStatusCode == true);
            Debug.Assert(optionsResponse1.Headers.TryGetValues("Access-Control-Allow-Origin", out var _vals) &&
                         _vals.First() == "https://fooboo.com/thingy");
            Debug.Assert(optionsResponse1.Headers.TryGetValues("Vary", out var vvals) && vvals.First() == "Origin");
            Debug.Assert(optionsResponse1?.Content.ReadAsStringAsync().Result.Length > 15);

            var optionsResponse2 = Http.Request("OPTIONS", "http://localhost:9000/rest/resource1", null,
                                                headers: new Dictionary <string, string> {
                ["Origin"] = "https://fooboo.com/invalid"
            });
            Debug.Assert(optionsResponse2?.Headers.TryGetValues("Access-Control-Allow-Origin", out var vals) == false);

            var optionsResponse3 = Http.Request("OPTIONS", "http://localhost:9000/rest/resource1", null);
            Debug.Assert(optionsResponse3?.IsSuccessStatusCode == true);
            Debug.Assert(optionsResponse3?.Content.ReadAsStringAsync().Result.Length > 15);

            #endregion

            #region XML

            Debug.Assert(Http.Request("GET", "http://localhost:9000/rest/resource2",
                                      headers: new Dictionary <string, string> {
                ["Accept"] = "application/xml"
            }).IsSuccessStatusCode);

            #endregion

            #region Error triggers

            //            Debug.Assert(Http.Request("GET", "http://localhost:9000/rest/x9").StatusCode == HttpStatusCode.NotFound);
            //            Debug.Assert(Http.Request("GET", "http://localhost:9000/rest/resource1/bfa=1").StatusCode == HttpStatusCode.NotFound);
            //            Debug.Assert(Http.Request("GET", "http://localhost:9000/rest/resource1//limit=foo").StatusCode == HttpStatusCode.BadRequest);
            //            Debug.Assert(Http.Request("POST", "http://localhost:9000/rest/resource1/bfa=1").StatusCode == HttpStatusCode.NotFound);
            //            Debug.Assert(Http.Request("POST", "http://localhost:9000/rest/resource1").StatusCode == HttpStatusCode.BadRequest);
            //            Debug.Assert(Http.Request("PATCH", "http://localhost:9000/rest/resource1").StatusCode == HttpStatusCode.BadRequest);
            //            Debug.Assert(Http.Request("POST", "http://localhost:9000/rest/myres", new byte[] {1, 2, 3}).StatusCode == HttpStatusCode.MethodNotAllowed);

            #endregion

            #region Events

            bool customraised = false;

            Events.Custom <ENotification> .Raise += (s, o) =>
            {
                Debug.Assert(s == null);
                Debug.Assert(o.Payload.Message?.Length == "Some message 1".Length);
                customraised = true;
            };

            var notifications = Db.Transact(() => new[]
            {
                new Notification {
                    Message = "Some message 1"
                }, new Notification {
                    Message = "Some message 2"
                },
                new Notification {
                    Message = "Some message 3"
                }, new Notification {
                    Message = "Some message 4"
                },
                new Notification {
                    Message = "Some message 5"
                }
            });

            var events = notifications
                         .Select(item => new ENotification(item))
                         .Union(new IEvent[]
            {
                new EString("This is the very important message!"),
                new EBytes(new byte[] { 4, 5, 1, 2, 3, 2, 3, 1, 5, 5, 1, 5, 1, 2, 3, 1, 2, 3, 1, 2, 1, 21, 5 }),
                new EStream(new MemoryStream(new byte[] { 4, 5, 1, 6, 7, 1, 8, 6, 8, 5, 8, 5, 8, 6, 8, 5 }))
            })
                         .ToList();

            // Raises all events
            foreach (dynamic e in events)
            {
                e.Invoke();
            }

            Task.Delay(5000).ContinueWith(_ =>
            {
                Debug.Assert(wrstreamcalled);
                Debug.Assert(wrbytescalled);
                Debug.Assert(wrstringcalled);
                Debug.Assert(customraised);
            }).Wait();

            #endregion

            var done = true;
        }