# Method: projects.test

Test `Source` for syntactic and semantic correctness. Issues present, if any, will be returned to the caller with a description, severity, and source location.

The test method may be executed with `Source`. Passing `Source` is useful for unit testing new rules.

Note that tests run using the REST API use production databases, storage buckets, and related resources. Such testing can incur usage charges. We strongly recommend that you use the Firebase Local Emulator Suite to perform Rules testing, since you can run tests on offline, non-production resources without usage charges.

The following is an example of `Source` that permits users to upload images to a bucket bearing their user id and matching the correct metadata:

_Example_

```javascript
// Users are allowed to subscribe and unsubscribe to the blog.
service firebase.storage {
  match /users/{userId}/images/{imageName} {
      allow write: if userId == request.auth.uid
          && (imageName.matches('*.png$')
          || imageName.matches('*.jpg$'))
          && resource.mimeType.matches('^image/')
  }
}
```

### HTTP request

`POST https://firebaserules.googleapis.com/v1/{name=projects/**}:test`

The URL uses [gRPC Transcoding](https://google.aip.dev/127) syntax.

### Path parameters

| Parameters |  
| --- |  
| `name` | `string`<br>Required. For tests against `source`, the resource name must refer to the project: Format: `projects/{project_id}` |

### Request body

The request body contains data with the following structure:

| JSON representation |
| --- |
| ```<br>{<br>  "source": {<br>    object (Source)<br>  },<br>  "testSuite": {<br>    object (TestSuite)<br>  }<br>}<br>``` |

| Fields |
| --- |
| `source` | `object (Source)`<br>`Source` to be checked for correctness. |
| `testSuite` | `object (TestSuite)`<br>The inline `TestSuite` to execute against the `Source`.<br>When `Source` is provided inline, the test cases will only be run if the `Source` is syntactically and semantically valid. |

### Response body

If successful, the response body contains data with the following structure:

The response for `FirebaseRulesService.TestRuleset`.

| JSON representation |
| --- |
| ```<br>{<br>  "issues": [<br>    {<br>      object (Issue)<br>    }<br>  ],<br>  "testResults": [<br>    {<br>      object (TestResult)<br>    }<br>  ]<br>}<br>``` |

| Fields |
| --- |
| `issues[]` | `object (Issue)`<br>Syntactic and semantic `Source` issues of varying severity. Issues of `ERROR` severity will prevent tests from executing. |
| `testResults[]` | `object (TestResult)`<br>The set of test results given the test cases in the `TestSuite`. The results will appear in the same order as the test cases appear in the `TestSuite`. |

### Authorization Scopes

Requires one of the following OAuth scopes:

- `https://www.googleapis.com/auth/cloud-platform`
- `https://www.googleapis.com/auth/firebase`
- `https://www.googleapis.com/auth/firebase.readonly`

For more information, see the [Authentication Overview](https://cloud.google.com/docs/authentication/).

## TestSuite

`TestSuite` is a collection of `TestCase` instances that validate the logical correctness of rules. The `TestSuite` may be referenced in-line within a `projects.test` invocation or as part of a `Release` object as a pre-release check.

| JSON representation |
| --- |
| ```<br>{<br>  "testCases": [<br>    {<br>      object (TestCase)<br>    }<br>  ]<br>}<br>``` |

| Fields |
| --- |
| `testCases[]` | `object (TestCase)`<br>Collection of test cases associated with the `TestSuite`. |

## TestCase

`TestCase` messages provide the request context and an expectation as to whether the given context will be allowed or denied. Test cases may specify the `request`, `resource`, and `functionMocks` to mock a function call to a service-provided function.

The `request` object represents context present at request-time.

The `resource` is the value of the target resource (e.g., metadata of a GCS object or Firestore document) as it appears in persistent storage before the request is executed.

| JSON representation |
| --- |
| ```<br>{<br>  "expectation": enum (Expectation),<br>  "request": value,<br>  "resource": value,<br>  "functionMocks": [<br>    {<br>      object (FunctionMock)<br>    }<br>  ],<br>  "pathEncoding": enum (PathEncoding),<br>  "expressionReportLevel": enum (ExpressionReportLevel)<br>}<br>``` |

| Fields |
| --- |
| `expectation` | `enum (Expectation)`<br>Test expectation. |
| `request` | `value (Value format)`<br>Request context.
| `resource` | `value (Value format)`<br>Optional resource value as it appears in persistent storage before the request is fulfilled.<br>The resource type depends on the `request.path` value. |
| `functionMocks[]` | `object (FunctionMock)`<br>Optional Rules function mocks for service-defined functions. If not set, any service-defined Rules function is expected to return an error, which may or may not influence the test outcome. |
| `pathEncoding` | `enum (PathEncoding)`<br>Specifies whether paths (such as request.path) are encoded and how. |
| `expressionReportLevel` | `enum (ExpressionReportLevel)`<br>Specifies what should be included in the response. |

## Expectation

The set of supported test case expectations.

| Enums |
| --- |
| `EXPECTATION_UNSPECIFIED` | Unspecified expectation. |
| `ALLOW` | Expect an allowed result. |
| `DENY` | Expect a denied result. |

## FunctionMock

Mock Rules function definition.

Mocks must refer to a function declared by the target service. The type of the function args and result will be inferred at test time. If either the arg or result values are not compatible with function type declaration, the request will be considered invalid.

More than one `FunctionMock` may be provided for a given function name so long as the `Arg` matchers are distinct. There may be only one function for a given overload where all `Arg` values are `Arg.any_value`.

See also [Functions in the Security Rules language](/content/docs/rules/rules-language#function/index.html).

| JSON representation |
| --- |
| ```<br>{<br>  "function": string,<br>  "args": [<br>    {<br>      object (Arg)<br>    }<br>  ],<br>  "result": {<br>    object (Result)<br>  }<br>}<br>``` |

| Fields |
| --- |
| `function` | `string`<br>The name of the function.<br>The function name must match one provided by a service declaration. |
| `args[]` | `object (Arg)`<br>The list of `Arg` values to match. The order in which the arguments are provided is the order in which they must appear in the function invocation. |
| `result` | `object (Result)`<br>The mock result of the function call. |

## Arg

Arg matchers for the mock function.

| JSON representation |
| --- |
| ```<br>{<br>  // Union field type can be only one of the following:<br>  "exactValue": value,<br>  "anyValue": {<br>    object<br>  }<br>  // End of list of possible types for union field type.<br>}<br>``` |

| Fields |
| --- |
| Union field `type`. Supported argument values. `type` can be only one of the following: |
| `exactValue` | `value (Value format)`<br>Argument exactly matches value provided. |
| `anyValue` | `object`<br>Argument matches any value provided. |

## Result

Possible result values from the function mock invocation.

| JSON representation |
| --- |
| ```<br>{<br>  // Union field type can be only one of the following:<br>  "value": value,<br>  "undefined": {<br>    object<br>  }<br>  // End of list of possible types for union field type.<br>}<br>``` |

| Fields |
| --- |
| Union field `type`. Supported result values. `type` can be only one of the following: |
| `value` | `value (Value format)`<br>The result is an actual value. The type of the value must match that of the type declared by the service. |
| `undefined` | `object`<br>The result is undefined, meaning the result could not be computed. |

## PathEncoding

The type of path encoding used.

| Enums |
| --- |
| `ENCODING_UNSPECIFIED` | No encoding has been specified. Defaults to "URL_ENCODED" behavior. |
| `URL_ENCODED` | Treats path segments as URL encoded but with non-encoded separators ("/"). This is the default behavior. |
| `PLAIN` | Treats total path as non-URL encoded e.g. raw. |

## ExpressionReportLevel

The amount of data to include in the expression report response.

| Enums |
| --- |
| `LEVEL_UNSPECIFIED` | No level has been specified. Defaults to "NONE" behavior. |
| `NONE` | Do not include any additional information. |
| `FULL` | Include detailed reporting on expressions evaluated. |
| `VISITED` | Only include the expressions that were visited during evaluation. |

## Issue

Issues include warnings, errors, and deprecation notices.

| JSON representation |
| --- |
| ```<br>{<br>  "sourcePosition": {<br>    object (SourcePosition)<br>  },<br>  "description": string,<br>  "severity": enum (Severity)<br>}<br>``` |

| Fields |
| --- |
| `sourcePosition` | `object (SourcePosition)`<br>Position of the issue in the `Source`. |
| `description` | `string`<br>Short error description. |
| `severity` | `enum (Severity)`<br>The severity of the issue. |

## SourcePosition

Position in the `Source` content including its line, column number, and an index of the `File` in the `Source` message. Used for debug purposes.

| JSON representation |
| --- |
| ```<br>{<br>  "fileName": string,<br>  "line": integer,<br>  "column": integer,<br>  "currentOffset": integer,<br>  "endOffset": integer<br>}<br>``` |

| Fields |
| --- |
| `fileName` | `string`<br>Name of the `File`. |
| `line` | `integer`<br>Line number of the source fragment. 1-based. |
| `column` | `integer`<br>First column on the source line associated with the source fragment. |
| `currentOffset` | `integer`<br>Start position relative to the beginning of the file. |
| `endOffset` | `integer`<br>End position relative to the beginning of the file. |

## Severity

The set of issue severities.

| Enums |
| --- |
| `SEVERITY_UNSPECIFIED` | An unspecified severity. |
| `DEPRECATION` | Deprecation issue for statements and method that may no longer be supported or maintained. |
| `WARNING` | Warnings such as: unused variables. |
| `ERROR` | Errors such as: unmatched curly braces or variable redefinition. |

## TestResult

Test result message containing the state of the test as well as a description and source position for test failures.

| JSON representation |
| --- |
| ```<br>{<br>  "state": enum (State),<br>  "debugMessages": [<br>    string<br>  ],<br>  "errorPosition": {<br>    object (SourcePosition)<br>  },<br>  "functionCalls": [<br>    {<br>      object (FunctionCall)<br>    }<br>  ],<br>  "visitedExpressions": [<br>    {<br>      object (VisitedExpression)<br>    }<br>  ],<br>  "expressionReports": [<br>    {<br>      object (ExpressionReport)<br>    }<br>  ]<br>}<br>``` |

| Fields |
| --- |
| `state` | `enum (State)`<br>State of the test. |
| `debugMessages[]` | `string`<br>Debug messages related to test execution issues encountered during evaluation.<br>Debug messages may be related to too many or too few invocations of function mocks or to runtime errors that occur during evaluation.<br>For example: `Unable to read variable [name: "resource"]` |
| `errorPosition` | `object (SourcePosition)`<br>Position in the `Source` where the principle runtime error occurs.<br>Evaluation of an expression may result in an error. Rules are deny by default, so a `DENY` expectation when an error is generated is valid. When there is a `DENY` with an error, the `SourcePosition` is returned.<br>E.g. `errorPosition { line: 19 column: 37 }` |
| `functionCalls[]` | `object (FunctionCall)`<br>The set of function calls made to service-defined methods.<br>Function calls are included in the order in which they are encountered during evaluation, are provided for both mocked and unmocked functions, and included on the response regardless of the test `state`. |
| `visitedExpressions[]` | `object (VisitedExpression)`<br>The set of visited permission expressions for a given test. This returns the positions and evaluation results of all visited permission expressions which were relevant to the test case, e.g.<br>```<br>match /path {<br>  allow read if: <expr><br>}<br>```<br>For a detailed report of the intermediate evaluation states, see the `expressionReports` field |
| `expressionReports[]` | `object (ExpressionReport)`<br>The mapping from expression in the ruleset AST to the values they were evaluated to. Partially-nested to mirror AST structure. Note that this field is actually tracking expressions and not permission statements in contrast to the "visitedExpressions" field above. Literal expressions are omitted. |

## State

Valid states for the test result.

| Enums |
| --- |
| `STATE_UNSPECIFIED` | Test state is not set. |
| `SUCCESS` | Test is a success. |
| `FAILURE` | Test is a failure. |

## FunctionCall

Represents a service-defined function call that was invoked during test execution.

| JSON representation |
| --- |
| ```<br>{<br>  "function": string,<br>  "args": [<br>    value<br>  ]<br>}<br>``` |

| Fields |
| --- |
| `function` | `string`<br>Name of the function invoked. |
| `args[]` | `value (Value format)`<br>The arguments that were provided to the function. |

## VisitedExpression

Store the position and access outcome for an expression visited in rules.

| JSON representation |
| --- |
| ```<br>{<br>  "sourcePosition": {<br>    object (SourcePosition)<br>  },<br>  "value": value<br>}<br>``` |

| Fields |
| --- |
| `sourcePosition` | `object (SourcePosition)`<br>Position in the `Source` where an expression was visited. |
| `value` | `value (Value format)`<br>The evaluated value for the visited expression, e.g. true/false |

## ExpressionReport

Describes where in a file an expression is found and what it was evaluated to over the course of its use.

| JSON representation |
| --- |
| ```<br>{<br>  "sourcePosition": {<br>    object (SourcePosition)<br>  },<br>  "values": [<br>    {<br>      object (ValueCount)<br>    }<br>  ],<br>  "children": [<br>    {<br>      object (ExpressionReport)<br>    }<br>  ]<br>}<br>``` |

| Fields |
| --- |
| `sourcePosition` | `object (SourcePosition)`<br>Position of expression in original rules source. |
| `values[]` | `object (ValueCount)`<br>Values that this expression evaluated to when encountered. |
| `children[]` | `object (ExpressionReport)`<br>Subexpressions |

## ValueCount

Tuple for how many times an Expression was evaluated to a particular ExpressionValue.

| JSON representation |
| --- |
| ```<br>{<br>  "value": value,<br>  "count": integer<br>}<br>``` |

| Fields |
| --- |
| `value` | `value (Value format)`<br>The return value of the expression |
| `count` | `integer`<br>The number of times that expression returned.
