Exemplo n.º 1
0
        public AstoriaServiceHost(Workspace workspace, string webDataServicePrefixName, string machineName, AstoriaDatabase database)
            : base(workspace, webDataServicePrefixName, machineName, database)
        {
            if (AstoriaTestProperties.Host == Host.IDSH || AstoriaTestProperties.Host == Host.IDSH2)
            {
                if (AstoriaTestProperties.HostAuthenicationMethod != "None")
                {
                    AstoriaTestLog.FailAndThrow("Test implementations of IDSH do not support authentication");
                }
            }

            waitHandleName      = waitHandlePrefix + identifier;
            serviceInstanceName = this.WebDataServicePrefixName + "_" + identifier;
            exeName             = serviceName + this.WebDataServicePrefixName;

            if (ProcessHelper.IsLocalMachine(this.MachineName))
            {
                DestinationFolder       = Path.Combine(serviceHostFolder, serviceInstanceName);
                DestinationFolder_Local = DestinationFolder;
                ExecutablePath          = Path.Combine(DestinationFolder, exeName + ".exe");
                localExecutablePath     = ExecutablePath;
            }
            else
            {
                string remoteMachineLocalPath = IISHelper.GetLocalMachineWWWRootSharePath(this.MachineName);
                DestinationFolder_Local = Path.Combine(IISHelper.GetLocalMachineWWWRootSharePath(this.MachineName), serviceInstanceName);
                DestinationFolder       = Path.Combine(IISHelper.GetWWWRootSharePath(this.MachineName), serviceInstanceName);
                ExecutablePath          = Path.Combine(DestinationFolder, exeName + ".exe");
                localExecutablePath     = Path.Combine(DestinationFolder_Local, exeName + ".exe");
            }

            rootUri = Uri.UriSchemeHttp + "://" + this.MachineName + ":7777";
        }
Exemplo n.º 2
0
        public void VerifyClient(QueryModel qm)
        {
            WebDataCtxWrapper ctx = new WebDataCtxWrapper(new Uri(qm.Workspace.ServiceUri));

            ctx.Credentials = CredentialCache.DefaultNetworkCredentials;

            try
            {
                UriQueryBuilder ub   = new UriQueryBuilder(qm.Workspace, "");
                string          ruri = ub.Build(qm.QueryResult);

                string uriRel = ruri.Substring(ruri.LastIndexOf(".svc/") + 5);

                if ((ctx.BaseUri + "/" + uriRel).Length > 260)
                {
                    return;
                }
                AstoriaTestLog.WriteLineIgnore(ctx.BaseUri + "/" + uriRel);

                ResolveClientType(qm.Workspace, ctx, qm.ResultType);

                object enumerable = ExecuteQuery(ctx, qm.ResultType, uriRel, "sync");
                Verify(qm.Workspace, qm.QueryResult, (IEnumerable)enumerable, qm.ResType, null, qm.IsCount);
            }
            catch (Exception e)
            {
                AstoriaTestLog.FailAndContinue(e);
            }
        }
Exemplo n.º 3
0
        public void GetKeyExpression()
        {
            if (_resType.Name.Contains("Order_Details_Extended") || _resourceContainer.Name.Contains("Order_Details_Extended"))
            {
                this.Result = null;
                return;
            }

            if (_resType.Name != _resourceContainer.BaseType.Name)
            {
                KeyExpressions keyExp2 = _resourceContainer.Workspace.GetExistingAssociatedKeys(_resourceContainer, _prop, _key);
                if (null == keyExp2 || keyExp2.Count == 0) /* no keys for resource type*/ return {
                    ;
                }
                foreach (KeyExpression ke in keyExp2)
                {
                    bool bSpecial = SpecialChars(ke);
                    if (bSpecial)
                    {
                        this.Result = null;
                        break;
                    }
                    else
                    {
                        this.Result = ke;
                        AstoriaTestLog.WriteLineIgnore("Predicate from container :" + _resType.Name);
                        break;
                    }
                }
            }
Exemplo n.º 4
0
        private void VerifyLoadProperty(object entity, string propertyName, WebDataCtxWrapper Context)
        {
            Uri entityUri = null;

            if (Context.TryGetUri(entity, out entityUri))
            {
                Uri  navigationPropertyURI = new Uri(String.Format("{0}/{1}", entityUri.OriginalString, propertyName));;
                Type navPropType           = entity.GetType().GetProperty(propertyName).PropertyType;
                if (navPropType.IsGenericType)
                {
                    navPropType = navPropType.GetGenericArguments()[0];
                }
                WebDataCtxWrapper baselineCOntext = new WebDataCtxWrapper(Context.BaseUri);
                baselineCOntext.Credentials = CredentialCache.DefaultCredentials;
                QueryOperationResponse qoResponse = baselineCOntext.ExecuteOfT(navPropType, navigationPropertyURI) as QueryOperationResponse;
                IEnumerator            enumerator = qoResponse.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    object baselineEntity   = enumerator.Current;
                    Uri    navPropEntityURI = null;
                    if (baselineCOntext.TryGetUri(baselineEntity, out navPropEntityURI))
                    {
                        AstoriaTestLog.IsNotNull(Context.TryGetEntityOfT(navPropType, navPropEntityURI), "Could not find entity in Navigation property ");
                    }
                }
            }
        }
Exemplo n.º 5
0
        internal static object GetSingleValueFromIQueryable(IQueryable querable, bool throwOnError)
        {
            object      val        = null;
            IEnumerator enumerator = querable.GetEnumerator();
            bool        moved      = enumerator.MoveNext();

            if (!moved && throwOnError)
            {
                throw new TestFailedException("Expected to find one result but none exist in Iqueryable");
            }
            else if (!moved && !throwOnError)
            {
                AstoriaTestLog.WriteLine("Error occured, cannot find a result in IQueryable");
                AstoriaTestLog.FailureFound = true;
            }
            else
            {
                val = enumerator.Current;
            }

            moved = enumerator.MoveNext();
            if (moved && throwOnError)
            {
                throw new TestFailedException("Expected to find one result but found 2 exist in Iqueryable");
            }
            else if (moved && !throwOnError)
            {
                AstoriaTestLog.WriteLine("Expected to find one result but found 2 exist in Iqueryable");
                AstoriaTestLog.FailureFound = true;
            }
            return(val);
        }
Exemplo n.º 6
0
        protected override void VerifyEntry(XmlNode entry)
        {
            //TODO: Astoria always returns type="application/xml" so this section is incomplete wrt spec and assunes xml content

            XmlNodeList contentNodes = entry.SelectNodes("atom:content", this.FormatVerifier.XmlNamespaceManager);

            if (contentNodes.Count != 1)
            {
                AstoriaTestLog.FailAndContinue(new TestFailedException("4.1.3 Content element: is missing"));
            }
            else
            {
                XmlNode contentNode = contentNodes[0];

                bool srcFound = contentNode.Attributes["src"] != null;

                if (contentNode.Attributes["type"] != null && contentNode.Attributes["type"].Value != "application/xml")
                {
                    AstoriaTestLog.FailAndContinue(new TestFailedException("4.1.3 Content element: type is not 'application/xml' (only supported value in v1 astoria)"));
                }

                if (contentNode.ChildNodes.Count != 1 && !srcFound)
                {
                    AstoriaTestLog.FailAndContinue(new TestFailedException("4.1.3.3 Content element: More than node found for conent root node."));
                }
            }
        }
Exemplo n.º 7
0
        protected override void VerifyEntry(XmlNode entry)
        {
            XmlNodeList categoryNodes = entry.SelectNodes("atom:category", this.FormatVerifier.XmlNamespaceManager);

            foreach (XmlNode categoryNode in categoryNodes)
            {
                XmlAttribute termAttrib = categoryNode.Attributes["term"];
                if (termAttrib == null)
                {
                    AstoriaTestLog.FailAndContinue(new TestFailedException("No term attribute found for Category node"));
                }

                /*else
                 * {
                 *  bool typeFound = false;
                 *  foreach (NodeType nodeType in _formatVerifier.Request.Workspace.Types.Where(t => t.ClrType.FullName == termAttrib.Value))
                 *  {
                 *      typeFound = true;
                 *      break;
                 *  }
                 *
                 *  if( !typeFound )
                 *      AstoriaTestLog.FailAndContinue(new TestFailedException("term attribute value (" + termAttrib.Value + ")is not valid type"));
                 * }*/
            }
        }
Exemplo n.º 8
0
 public static void VerifyConcurrency(AstoriaResponse response)
 {
     if (response.Request.ETagHeaderExpected)
     {
         if (!response.ETagHeaderFound && !RequestUtil.ExpectEmptyHeaders(response))
         {
             AstoriaTestLog.FailAndThrow("Missing ETag header in response");
         }
     }
     else if (response.ETagHeaderFound)
     {
         if (string.IsNullOrEmpty(response.ETagHeader))
         {
             if (Versioning.Server.BugFixed_NullETagWhenTypeHasNoConcurrency)
             {
                 AstoriaTestLog.FailAndThrow("Unexpected null ETag header in response");
             }
             else
             {
                 AstoriaTestLog.WriteLine("Ignoring unexpected null ETag header in response due to known bug");
             }
         }
         else
         {
             AstoriaTestLog.FailAndThrow("Unexpected ETag header in response: '" + response.ETagHeader + "'");
         }
     }
 }
Exemplo n.º 9
0
        private static void VerifyLinksPayload(Workspace w, CommonPayload payload, LinqQueryBuilder linqBuilder)
        {
            ArrayList expectedEntities = CommonPayload.CreateList(linqBuilder.QueryResult);

            if (payload == null)
            {
                AstoriaTestLog.AreEqual(expectedEntities.Count, 0, "Unexpected null $ref payload");
            }
            else
            {
                KeyExpressions expectedKeys = new KeyExpressions();
                foreach (object o in expectedEntities)
                {
                    KeyExpression keyExp = w.CreateKeyExpressionFromProviderObject(o);
                    expectedKeys.Add(keyExp);
                }

                List <string> linksFound = new List <string>();

                if (payload.Resources == null)
                {
                    linksFound.Add(payload.Value);
                }
                else
                {
                    foreach (PayloadObject o in (payload.Resources as List <PayloadObject>))
                    {
                        if (o.PayloadProperties.Any(p => p.Name == "uri"))
                        {
                            linksFound.Add((o["uri"] as PayloadSimpleProperty).Value);
                        }
                    }
                }

                AstoriaTestLog.AreEqual(expectedKeys.Count, linksFound.Count, "Number of expected entities does not match number of links found");

                foreach (string link in linksFound)
                {
                    KeyExpression match = null;
                    foreach (KeyExpression expectedKey in expectedKeys)
                    {
                        if (compareKeyURI(link, expectedKey))
                        {
                            match = expectedKey;
                            break;
                        }
                    }

                    if (match != null)
                    {
                        expectedKeys.Remove(match);
                    }
                    else
                    {
                        AstoriaTestLog.WriteLineIgnore("Unexpected URI: '" + link + "'");
                        AstoriaTestLog.FailAndThrow("Unexpected URI found in $ref payload");
                    }
                }
            }
        }
Exemplo n.º 10
0
        public void VerifyServer(ExpNode q)
        {
            AstoriaTestLog.WriteLineIgnore("Verify server query");
            try
            {
                UriQueryBuilder ub   = new UriQueryBuilder(_workspace, "");
                string          ruri = ub.Build(q);
                AstoriaTestLog.WriteLineIgnore(ruri);


                AstoriaRequest request = _workspace.CreateRequest(q);
                request.Format = _kind;

                if (request.URI.Length > 260)
                {
                    return;
                }

                AstoriaResponse response = request.GetResponse();
                response.Verify();
            }
            catch (Exception e)
            {
                AstoriaTestLog.WriteLineIgnore(e.ToString());
            }
        }
Exemplo n.º 11
0
        public void Verify(string payload)
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(payload);

            XmlNode authorNode = xmlDocument.SelectNodes("atom:author", _formatVerifier.XmlNamespaceManager)[0];

            // atom:author elements MUST contain exactly one atom:name element.
            XmlNodeList childNodes = authorNode.SelectNodes("atom:name", _formatVerifier.XmlNamespaceManager);

            if (childNodes.Count != 1)
            {
                AstoriaTestLog.FailAndContinue(new TestFailedException("3.2.1 atomPersonConstruct element: Not exactly 1 name node found for atomPersonConstruct."));
            }

            // atom:author elements MAY contain exactly one atom:uri element.
            childNodes = authorNode.SelectNodes("atom:uri", _formatVerifier.XmlNamespaceManager);
            if (childNodes.Count > 1)
            {
                AstoriaTestLog.FailAndContinue(new TestFailedException("3.2.1 atomPersonConstruct element: Greater than 1 uri node found for atomPersonConstruct."));
            }

            // atom:author elements MAY contain exactly one atom:email element.
            childNodes = authorNode.SelectNodes("atom:email", _formatVerifier.XmlNamespaceManager);
            if (childNodes.Count > 1)
            {
                AstoriaTestLog.FailAndContinue(new TestFailedException("3.2.1 atomPersonConstruct element: Greater than 1 email node found for atomPersonConstruct."));
            }
        }
Exemplo n.º 12
0
        protected override void Verify()
        {
            if (!Applies(Response))
            {
                return;
            }

            AstoriaRequest request = Response.Request;

            if (!request.SnapshotForUpdate)
            {
                return;
            }

            try
            {
                Verify(request);
            }
            catch (Exception e)
            {
                AstoriaTestLog.WriteLineIgnore("Pre-update snapshot:");
                AstoriaTestLog.WriteLineIgnore(request.BeforeUpdatePayload.RawPayload);
                AstoriaTestLog.WriteLineIgnore("--------------------");
                AstoriaTestLog.WriteLineIgnore("Post-update snapshot:");
                AstoriaTestLog.WriteLineIgnore(request.AfterUpdatePayload.RawPayload);

                throw new TestFailedException("Update verification failed", null, null, e);
            }
        }
Exemplo n.º 13
0
        private static void CompareEdmType(IEdmType edmEdmType, IEdmType dataWebEdmType, bool isReflectionBasedProvider, out int numberOfNavProps)
        {
            if (edmEdmType == null)
            {
                throw new ArgumentNullException("edmEdmType");
            }
            if (dataWebEdmType == null)
            {
                throw new ArgumentNullException("dataWebEdmType");
            }

            AstoriaTestLog.IsTrue(edmEdmType.TypeKind == EdmTypeKind.Entity ||
                                  edmEdmType.TypeKind == EdmTypeKind.Complex,
                                  "Only structural type expected - " + edmEdmType.TypeKind.ToString());

            AstoriaTestLog.IsTrue(edmEdmType.TypeKind == dataWebEdmType.TypeKind,
                                  "BuiltInTypeKind must be the name");

            if (edmEdmType.TypeKind == EdmTypeKind.Entity)
            {
                List <IEdmStructuralProperty> edmKeyMembers     = ((IEdmEntityType)edmEdmType).Key().ToList();
                List <IEdmStructuralProperty> dataWebKeyMembers = ((IEdmEntityType)dataWebEdmType).Key().ToList();

                AstoriaTestLog.IsTrue(edmKeyMembers.Count == dataWebKeyMembers.Count, "Key members count must match");
                foreach (IEdmStructuralProperty member1 in edmKeyMembers)
                {
                    // make sure the member with the same name in the key members list
                    // Other comparisions will be done in the member comparison
                    AstoriaTestLog.IsTrue(dataWebKeyMembers.Any(p => p.Name == member1.Name));
                }
            }

            CompareMembers((IEdmStructuredType)edmEdmType, (IEdmStructuredType)dataWebEdmType, isReflectionBasedProvider, out numberOfNavProps);
        }
Exemplo n.º 14
0
        //---------------------------------------------------------------------
        // Replaces existing method code with that from embedded resources.
        //---------------------------------------------------------------------
        protected string ReplaceCode(string existingCode, string methodRegex, string resourceName)
        {
            // Find embedded resource.
            foreach (string fullName in GetType().Assembly.GetManifestResourceNames())
            {
                if (fullName.Contains(resourceName))
                {
                    // Replace type resolver.
                    using (StreamReader reader = new StreamReader(GetType().Assembly.GetManifestResourceStream(fullName), true))
                    {
                        // Read new code from resources.
                        string newCode = reader.ReadToEnd();

                        // Find method signature in existing code and replace
                        Regex method = new Regex(methodRegex, RegexOptions.Singleline);
                        if (method.Match(existingCode).Success)
                        {
                            return(method.Replace(existingCode, newCode));
                        }

                        AstoriaTestLog.FailAndThrow("Test error: unable to match " + methodRegex + " in embedded code: " + existingCode);
                        return(null);
                    }
                }
            }
            AstoriaTestLog.FailAndThrow("Test error: unable to find embedded resource: " + existingCode);
            return(null);
        }
Exemplo n.º 15
0
 internal static Workspaces GetWorkspacesFilteredByTestProperties(Action <Workspace> beforeWorkspaceCreate)
 {
     if (_workspaceCreationFailed)
     {
         throw new TestFailedException("Workspaces failed on creation previously");
     }
     if (_filteredWorkspaces == null)
     {
         try
         {
             _filteredWorkspaces = CreateFilteredWorkspaces(AstoriaTestProperties.DataLayerProviderKinds, AstoriaTestProperties.MaxPriority, true, beforeWorkspaceCreate);
         }
         catch (System.Reflection.ReflectionTypeLoadException typeloadException)
         {
             _workspaceCreationFailed = true;
             AstoriaTestLog.WriteLine("LoaderExceptions:");
             foreach (Exception exc in typeloadException.LoaderExceptions)
             {
                 AstoriaTestLog.FailAndContinue(exc);
             }
             throw typeloadException;
         }
         catch (Exception exc)
         {
             _workspaceCreationFailed = true;
             throw;
         }
     }
     return(_filteredWorkspaces);
 }
Exemplo n.º 16
0
        private static void CompareMembers(IEdmStructuredType edmEdmType, IEdmStructuredType dataWebEdmType, bool isReflectionBasedProvider, out int totalNavProps)
        {
            // find the number of nav properties on this type (not the base type). This will help us to determine how many associations
            // be generated
            totalNavProps = edmEdmType.DeclaredProperties.OfType <IEdmNavigationProperty>().Count();
            AstoriaTestLog.IsTrue(edmEdmType.DeclaredProperties.Count() == dataWebEdmType.DeclaredProperties.Count(), "Number of members must match");

            foreach (IEdmProperty member1 in edmEdmType.DeclaredProperties)
            {
                IEdmProperty member2 = dataWebEdmType.FindProperty(member1.Name);
                AstoriaTestLog.IsNotNull(member2);

                // WCF DS server will always write DateTimeOffset as the data type, if the backend model has DateTime as the data type
                string edmMemberTypeName = member1.Type.FullName();
                if (edmMemberTypeName == "Edm.DateTime")
                {
                    AstoriaTestLog.IsTrue(member2.Type.FullName() == "Edm.DateTimeOffset", "For DateTime properties in the model, we should generate");
                }
                else
                {
                    AstoriaTestLog.IsTrue(edmMemberTypeName == member2.Type.FullName(), "Type must match");
                }

                AstoriaTestLog.IsTrue(member1.Type.IsNullable == member2.Type.IsNullable, "nullability must match");

                // TODO: if its a navigation, compare referential constraint!
            }
        }
Exemplo n.º 17
0
 //---------------------------------------------------------------------
 // Adds code from embedded resources to data service source file.
 //---------------------------------------------------------------------
 protected void InjectCode(Workspace w, params string[] resourceNames)
 {
     foreach (string resourceName in resourceNames)
     {
         // Find embedded resource.
         bool found = false;
         foreach (string fullName in GetType().Assembly.GetManifestResourceNames())
         {
             if (fullName.Contains(resourceName))
             {
                 // Append contents to service code.
                 using (StreamReader reader = new StreamReader(GetType().Assembly.GetManifestResourceStream(fullName), true))
                 {
                     w.GlobalAdditionalCode += reader.ReadToEnd();
                     found = true;
                     break;
                 }
             }
         }
         if (!found)
         {
             AstoriaTestLog.FailAndThrow("Test error: embedded resource not found!");
         }
     }
 }
Exemplo n.º 18
0
        public void LogResponse()
        {
            StringBuilder builder = new StringBuilder();

            LogResponse(builder, true, false);
            AstoriaTestLog.WriteIgnore(builder.ToString());
        }
Exemplo n.º 19
0
 // Print out the WCF configuration option values if different from default setting
 public void LogConfigSetting()
 {
     if (!_TransferMode.Equals("Buffered") ||
         _MaxBufferSize != 2147483647 ||
         _MaxReceivedMessageSize != 2147483647 ||
         _MaxRequestLength != 2097151 ||
         !_TransportSecurityMode.Equals("TransportCredentialOnly") ||
         !_CloseTimeout.Equals("00:01:00") ||
         !_OpenTimeout.Equals("00:01:00") ||
         !_ReceiveTimeout.Equals("00:10:00") ||
         !_SendTimeout.Equals("00:01:00") ||
         !_AspNetCompatibilityEnabled)
     {
         AstoriaTestLog.WriteLineIgnore("WCF Configuration Settings:");
         AstoriaTestLog.WriteLineIgnore("_TransferMode: " + _TransferMode);
         AstoriaTestLog.WriteLineIgnore("_MaxBufferSize: " + _MaxBufferSize);
         AstoriaTestLog.WriteLineIgnore("_MaxReceivedMessageSize: " + _MaxReceivedMessageSize);
         AstoriaTestLog.WriteLineIgnore("_MaxRequestLength: " + _MaxRequestLength);
         AstoriaTestLog.WriteLineIgnore("_TransportSecurityMode: " + _TransportSecurityMode);
         AstoriaTestLog.WriteLineIgnore("_CloseTimeout: " + _CloseTimeout);
         AstoriaTestLog.WriteLineIgnore("_OpenTimeout: " + _OpenTimeout);
         AstoriaTestLog.WriteLineIgnore("_ReceiveTimeout: " + _ReceiveTimeout);
         AstoriaTestLog.WriteLineIgnore("_SendTimeout: " + _SendTimeout);
         AstoriaTestLog.WriteLineIgnore("_AspNetCompatibilityEnabled: " + _AspNetCompatibilityEnabled);
     }
 }
Exemplo n.º 20
0
        public virtual void CompareSingleValue(object expected, bool stripQuotes, bool valueUri)
        {
            if (this.Resources == null && expected == null)
            {
                return;
            }

            PayloadSimpleProperty simpleProperty = this.Resources as PayloadSimpleProperty;

            if (simpleProperty == null)
            {
                AstoriaTestLog.FailAndThrow("Payload did not represent a single value");
            }

            if (expected == null)
            {
                if (!simpleProperty.IsNull)
                {
                    AstoriaTestLog.FailAndContinue(new TestFailedException("Compare failed - Expected: null, got: " + simpleProperty.Value));
                }
            }
            else
            {
                ComparePrimitiveValuesObjectAndString(expected, expected.GetType(), simpleProperty.Value, valueUri, this.Format, false);
            }
        }
Exemplo n.º 21
0
        // Turns a resource type into an MLE.
        private static void MakeMLE(Workspace w, string typeName)
        {
            // Add blob attribute.
            ResourceType type = w.ServiceContainer.ResourceTypes.Where(p => p.Name == typeName).First();

            type.Facets.Add(NodeFacet.Attribute(new BlobsAttribute(type)));
            AstoriaTestLog.WriteLineIgnore("MLE type: " + type.Name);
        }
Exemplo n.º 22
0
        public void LogRequest()
        {
            StringBuilder builder = new StringBuilder();

            LogRequest(builder, !Workspace.Settings.SuppressTrivialLogging);

            AstoriaTestLog.WriteIgnore(builder.ToString());
        }
Exemplo n.º 23
0
        private void VerifyInsertResponse(ResourceType type, PayloadObject inserted, PayloadObject returned)
        {
            // need to 'follow' deferred links to ensure that they're correct
            // doesn't need to match exactly
            AstoriaTestLog.AreEqual(inserted.Type, returned.Type, "Types do not match");

            VerifyProperties(type, inserted, returned, true, (rp => !rp.Facets.ServerGenerated));
        }
Exemplo n.º 24
0
 /// <summary>
 /// Constructs a new CodeGeneratingDataInserter for the given workspace
 /// </summary>
 /// <param name="w">the worspace to add data to</param>
 public CodeGeneratingDataInserter(Workspace w)
 {
     if (w.DataLayerProviderKind != DataLayerProviderKind.InMemoryLinq && w.DataLayerProviderKind != DataLayerProviderKind.NonClr)
     {
         AstoriaTestLog.FailAndThrow("CodeGeneratingDataInserter only supported for InMemory and NonClr workspaces");
     }
     workspace = w;
 }
Exemplo n.º 25
0
        //---------------------------------------------------------------------
        // Sends and verifies request for all possible access rights.
        //---------------------------------------------------------------------
        public void TestAccess(string container)
        {
            // Save current state.
            HttpStatusCode normalStatusCode = ExpectedStatusCode;

#if !ClientSKUFramework
            for (uint i = 0; i <= (uint)Microsoft.OData.Service.EntitySetRights.All; i++)
            {
                // Set entity set access right.
                Workspace.DataService.ConfigSettings.SetEntitySetAccessRule(container, (Microsoft.OData.Service.EntitySetRights)i);

                // Calculate minimum access needed for request to succeed.
                Microsoft.OData.Service.EntitySetRights minAccess = Microsoft.OData.Service.EntitySetRights.All;
                switch (Verb)
                {
                case RequestVerb.Post: minAccess = Microsoft.OData.Service.EntitySetRights.WriteAppend; break;

                case RequestVerb.Get: minAccess = Microsoft.OData.Service.EntitySetRights.ReadSingle; break;

                case RequestVerb.Put: minAccess = Microsoft.OData.Service.EntitySetRights.WriteReplace | Microsoft.OData.Service.EntitySetRights.ReadSingle; break;

                case RequestVerb.Patch: minAccess = Microsoft.OData.Service.EntitySetRights.WriteMerge | Microsoft.OData.Service.EntitySetRights.ReadSingle; break;

                case RequestVerb.Delete: minAccess = Microsoft.OData.Service.EntitySetRights.WriteDelete | Microsoft.OData.Service.EntitySetRights.ReadSingle; break;

                default:
                    AstoriaTestLog.FailAndThrow("Test issue - unknown request verb (2)");
                    break;
                }

                // Calculate expected status code.
                ExpectedStatusCode =
                    i == 0 ? HttpStatusCode.NotFound
                    : (i & (uint)minAccess) == (uint)minAccess ? normalStatusCode : HttpStatusCode.Forbidden;

                // Send and verify request.
                AstoriaResponse response = SendAndVerify(null);

                // Delete the entity if it was created to avoid "key already exists" collisions.
                if (response.Headers.ContainsKey("Location"))
                {
                    string newEntity = response.Headers["Location"];

                    Workspace.DataService.ConfigSettings.SetEntitySetAccessRule(container, Microsoft.OData.Service.EntitySetRights.WriteDelete | Microsoft.OData.Service.EntitySetRights.ReadSingle);


                    BlobsRequest.MLE(Workspace, Format, RequestVerb.Delete, null, HttpStatusCode.NoContent, newEntity).SendAndVerify(null);
                }
            }
#endif


            // Restore previous state.
            ExpectedStatusCode = normalStatusCode;
#if !ClientSKUFramework
            Workspace.DataService.ConfigSettings.SetEntitySetAccessRule(container, Microsoft.OData.Service.EntitySetRights.All);
#endif
        }
Exemplo n.º 26
0
        public static T Execute <T>(Func <T> f, bool inWebRequest, out System.Net.WebException exc)
        {
            exc = null;
            for (int i = 0; i < SocketExceptionRetries; i++)
            {
                try
                {
                    exc = null;
                    return(TrustedMethods.ReturnFuncResult <T>(f));
                }
                catch (WebException ex)
                {
                    exc = ex;
                    if (ex.InnerException is SocketException)
                    {
                        HandleSocketException(inWebRequest, (SocketException)exc.InnerException);
                    }
                    else
                    {
                        if (inWebRequest)
                        {
                            return(default(T)); // it will handle this
                        }
                        if (ex.Status == WebExceptionStatus.Timeout && CatchTimeouts)
                        {
                            HandleWebRequestTimeout(inWebRequest, ex);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException == null || !(ex.InnerException is System.Net.WebException))
                    {
                        throw ex;
                    }

                    exc = (WebException)ex.InnerException;
                    if (exc.InnerException != null && (exc.InnerException is SocketException))
                    {
                        HandleSocketException(inWebRequest, (SocketException)exc.InnerException);
                    }
                    else if (exc.Status == WebExceptionStatus.Timeout && CatchTimeouts)
                    {
                        HandleWebRequestTimeout(inWebRequest, exc);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            AstoriaTestLog.FailAndThrow("Repeated socket exceptions encountered, consequences unpredictable.");
            return(default(T));
        }
Exemplo n.º 27
0
        private void VerifyQueryResponse(ResourceType type, PayloadObject fromInsert, PayloadObject fromQuery)
        {
            bool keyShouldMatch = true;

            if (type.Key.Properties.Any(p => p.Facets.FixedLength))
            {
                foreach (NodeProperty property in type.Key.Properties.Where(p => p.Facets.FixedLength))
                {
                    // this may not always be correct for all types, but it seems to work most of the time;
                    int length;
                    if (property.Facets.MaxSize.HasValue)
                    {
                        length = property.Facets.MaxSize.Value;
                    }
                    else if (property.Type == Clr.Types.Decimal)
                    {
                        length = property.Facets.Precision.Value + property.Facets.Scale.Value;
                    }
                    else
                    {
                        continue;
                    }

                    string value = null;
                    if (fromInsert.PayloadProperties.Any(p => p.Name == property.Name))
                    {
                        value = (fromInsert[property.Name] as PayloadSimpleProperty).Value;
                    }
                    else
                    {
                        value = fromInsert.CustomEpmMappedProperties[property.Name];
                    }

                    if (value != null && value.Length < length)
                    {
                        keyShouldMatch = false;
                    }
                }
            }

            if (keyShouldMatch)
            {
                AstoriaTestLog.AreEqual(fromInsert.AbsoluteUri, fromQuery.AbsoluteUri, "fromInsert.AbsoluteUri != fromQuery.AbsoluteUri", false);
            }
            else
            {
                AstoriaTestLog.IsFalse(fromInsert.AbsoluteUri == fromQuery.AbsoluteUri, "fromInsert.AbsoluteUri == fromQuery.AbsoluteUri, despite fixed-length string");
            }

            // leave it to the concurrency tests to check the more involved etags
            if (!type.Properties.Any(p => p.Facets.ConcurrencyModeFixed && p.Facets.FixedLength))
            {
                AstoriaTestLog.AreEqual(fromInsert.ETag, fromQuery.ETag, "fromInsert.ETag != fromQuery.ETag", false);
            }

            VerifyProperties(type, fromInsert, fromQuery, false, rp => true);
        }
Exemplo n.º 28
0
        public static void Verify(APICallLogBuilder callLogBuilder, AstoriaResponse response, params ComplexType[] types)
        {
            if (!response.Request.LogAPICalls)
            {
                AstoriaTestLog.FailAndThrow("Cannot verify call order when the request did not log the calls");
            }

            Verify(callLogBuilder, response, Equal, types);
        }
Exemplo n.º 29
0
        public static BatchResponse ParseBatchResponse(BatchRequest batchRequest, StringReader reader, string boundary)
        {
            // even if content-id is specified, we may not get it back in error cases. This doesn't feel entirely correct, it seems like there should
            // always be a 1-1 mapping that explicitly honors content-id's

            // TODO: responses / requests without content IDs should be matched up in order within changeset only
            // changesets should have the right number of responses too

            BatchResponse           response           = null;// new BatchResponse(batchRequest);
            List <ResponseFragment> unmatchedFragments = new List <ResponseFragment>();
            List <AstoriaRequest>   unmatchedRequests  = batchRequest.Requests
                                                         .Union(batchRequest.Changesets.SelectMany(changeset => changeset.AsEnumerable()))
                                                         .ToList();

            foreach (ResponseFragment fragment in ParseBatchResponse(reader, boundary))
            {
                AstoriaRequest request = null;

                if (fragment.ContentID != null)
                {
                    request = unmatchedRequests
                              .FirstOrDefault(r => r.Headers.ContainsKey("Content-ID") &&
                                              r.Headers["Content-ID"].Equals(fragment.ContentID));
                }

                if (request == null)
                {
                    unmatchedFragments.Add(fragment);
                }
                else
                {
                    unmatchedRequests.Remove(request);

                    response.Responses.Add(FragmentToResponse(request, fragment));
                }
            }

            if (unmatchedFragments.Any())
            {
                if (unmatchedFragments.Count < unmatchedRequests.Count)
                {
                    AstoriaTestLog.WriteLine("Warning: recieved fewer batch response fragments than expected");
                }
                else if (unmatchedFragments.Count > unmatchedRequests.Count)
                {
                    AstoriaTestLog.FailAndThrow("Recieved more batch fragments than expected");
                }

                for (int i = 0; i < unmatchedFragments.Count; i++)
                {
                    response.Responses.Add(FragmentToResponse(unmatchedRequests[i], unmatchedFragments[i]));
                }
            }

            return(response);
        }
Exemplo n.º 30
0
        public static void VerifySpecificResponseVersion(AstoriaResponse response, int major, int minor)
        {
            if (response.DataServiceVersion == null)
            {
                AstoriaTestLog.FailAndThrow("Data service version should always be specified in response");
            }

            AstoriaTestLog.IsTrue(response.DataServiceVersion.StartsWith(major + "." + minor),
                                  String.Format("Unexpected value in response's DataServiceVersion header: {0}, expected: {1}.{2}", response.DataServiceVersion, major, minor));
        }