Method: projects.test

TestSource 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 withSource. PassingSource is useful for unit testing new rules.

Note that tests run using the REST API use production databases, storage buckets, and related rsesources. 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 ofSource that permits users to upload images to a bucket bearing their user id and matching the correct metadata:

Example

// 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 usesgRPC Transcoding syntax.

Path parameters

Parameters
name

string

Required. For tests againstsource, 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
{"source":{object (Source)},"testSuite":{object (TestSuite)}}
Fields
source

object (Source)

Source to be checked for correctness.

testSuite

object (TestSuite)

The inlineTestSuite to execute against theSource.

WhenSource is provided inline, the test cases will only be run if theSource is syntactically and semantically valid.

Response body

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

The response forFirebaseRulesService.TestRuleset.

JSON representation
{"issues":[{object (Issue)}],"testResults":[{object (TestResult)}]}
Fields
issues[]

object (Issue)

Syntactic and semanticSource issues of varying severity. Issues ofERROR severity will prevent tests from executing.

testResults[]

object (TestResult)

The set of test results given the test cases in theTestSuite. The results will appear in the same order as the test cases appear in theTestSuite.

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 theAuthentication Overview.

TestSuite

TestSuite is a collection ofTestCase instances that validate the logical correctness of rules. TheTestSuite may be referenced in-line within aprojects.test invocation or as part of aRelease object as a pre-release check.

JSON representation
{"testCases":[{object (TestCase)}]}
Fields
testCases[]

object (TestCase)

Collection of test cases associated with theTestSuite.

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 therequest,resosurce, andfunctionMocks to mock a function call to a service-provided function.

Therequest object represents context present at request-time.

Theresource 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.

See also the related reference documentation for Cloud Firestore ( request,resource) and Cloud Storage for Firebase (request,resource).

JSON representation
{"expectation":enum (Expectation),"request":value,"resource":value,"functionMocks":[{object (FunctionMock)}],"pathEncoding":enum (PathEncoding),"expressionReportLevel":enum (ExpressionReportLevel)}
Fields
expectation

enum (Expectation)

Test expectation.

request

value (Value format)

Request context.

The exact format of the request context is service-dependent. See the appropriate service documentation for information about the supported fields and types on the request. Minimally, all services support the following fields and types:

Request fieldType
auth.uidstring
auth.tokenmap<string, string>
headersmap<string, string>
methodstring
paramsmap<string, string>
pathstring
timegoogle.protobuf.Timestamp

If the request value is not well-formed for the service, the request will be rejected as an invalid argument.

resource

value (Value format)

Optional resource value as it appears in persistent storage before the request is fulfilled.

The resource type depends on therequest.path value.

functionMocks[]

object (FunctionMock)

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)

Specifies whether paths (such as request.path) are encoded and how.

expressionReportLevel

enum (ExpressionReportLevel)

Specifies what should be included in the response.

Expectation

The set of supported test case expectations.

Enums
EXPECTATION_UNSPECIFIEDUnspecified expectation.
ALLOWExpect an allowed result.
DENYExpect 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 oneFunctionMock may be provided for a given function name so long as theArg matchers are distinct. There may be only one function for a given overload where allArg values areArg.any_value.

See alsoFunctions in the Security Rules language.

JSON representation
{"function":string,"args":[{object (Arg)}],"result":{object (Result)}}
Fields
function

string

The name of the function.

The function name must match one provided by a service declaration.

args[]

object (Arg)

The list ofArg 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)

The mock result of the function call.

Arg

Arg matchers for the mock function.

JSON representation
{// Union fieldtype can be only one of the following:"exactValue":value,"anyValue":{object}// End of list of possible types for union fieldtype.}
Fields
Union fieldtype. Supported argument values.type can be only one of the following:
exactValue

value (Value format)

Argument exactly matches value provided.

anyValue

object

Argument matches any value provided.

Result

Possible result values from the function mock invocation.

JSON representation
{// Union fieldtype can be only one of the following:"value":value,"undefined":{object}// End of list of possible types for union fieldtype.}
Fields
Union fieldtype. Supported result values.type can be only one of the following:
value

value (Value format)

The result is an actual value. The type of the value must match that of the type declared by the service.

undefined

object

The result is undefined, meaning the result could not be computed.

PathEncoding

The type of path encoding used.

Enums
ENCODING_UNSPECIFIEDNo encoding has been specified. Defaults to "URL_ENCODED" behavior.
URL_ENCODEDTreats path segments as URL encoded but with non-encoded separators ("/"). This is the default behavior.
PLAINTreats total path as non-URL encoded e.g. raw.

ExpressionReportLevel

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

Enums
LEVEL_UNSPECIFIEDNo level has been specified. Defaults to "NONE" behavior.
NONEDo not include any additional information.
FULLInclude detailed reporting on expressions evaluated.
VISITEDOnly include the expressions that were visited during evaluation.

Issue

Issues include warnings, errors, and deprecation notices.

JSON representation
{"sourcePosition":{object (SourcePosition)},"description":string,"severity":enum (Severity)}
Fields
sourcePosition

object (SourcePosition)

Position of the issue in theSource.

description

string

Short error description.

severity

enum (Severity)

The severity of the issue.

SourcePosition

Position in theSource content including its line, column number, and an index of theFile in theSource message. Used for debug purposes.

JSON representation
{"fileName":string,"line":integer,"column":integer,"currentOffset":integer,"endOffset":integer}
Fields
fileName

string

Name of theFile.

line

integer

Line number of the source fragment. 1-based.

column

integer

First column on the source line associated with the source fragment.

currentOffset

integer

Start position relative to the beginning of the file.

endOffset

integer

End position relative to the beginning of the file.

Severity

The set of issue severities.

Enums
SEVERITY_UNSPECIFIEDAn unspecified severity.
DEPRECATIONDeprecation issue for statements and method that may no longer be supported or maintained.
WARNINGWarnings such as: unused variables.
ERRORErrors 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
{"state":enum (State),"debugMessages":[string],"errorPosition":{object (SourcePosition)},"functionCalls":[{object (FunctionCall)}],"visitedExpressions":[{object (VisitedExpression)}],"expressionReports":[{object (ExpressionReport)}]}
Fields
state

enum (State)

State of the test.

debugMessages[]

string

Debug messages related to test execution issues encountered during evaluation.

Debug messages may be related to too many or too few invocations of function mocks or to runtime errors that occur during evaluation.

For example:Unable to read variable [name: "resource"]

errorPosition

object (SourcePosition)

Position in theSource where the principle runtime error occurs.

Evaluation of an expression may result in an error. Rules are deny by default, so aDENY expectation when an error is generated is valid. When there is aDENY with an error, theSourcePosition is returned.

E.g.errorPosition { line: 19 column: 37 }

functionCalls[]

object (FunctionCall)

The set of function calls made to service-defined methods.

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 teststate.

visitedExpressions[]

object (VisitedExpression)

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.

match /path {  allow read if: <expr>}

For a detailed report of the intermediate evaluation states, see theexpressionReports field

expressionReports[]

object (ExpressionReport)

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_UNSPECIFIEDTest state is not set.
SUCCESSTest is a success.
FAILURETest is a failure.

FunctionCall

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

JSON representation
{"function":string,"args":[value]}
Fields
function

string

Name of the function invoked.

args[]

value (Value format)

The arguments that were provided to the function.

VisitedExpression

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

JSON representation
{"sourcePosition":{object (SourcePosition)},"value":value}
Fields
sourcePosition

object (SourcePosition)

Position in theSource where an expression was visited.

value

value (Value format)

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
{"sourcePosition":{object (SourcePosition)},"values":[{object (ValueCount)}],"children":[{object (ExpressionReport)}]}
Fields
sourcePosition

object (SourcePosition)

Position of expression in original rules source.

values[]

object (ValueCount)

Values that this expression evaluated to when encountered.

children[]

object (ExpressionReport)

Subexpressions

ValueCount

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

JSON representation
{"value":value,"count":integer}
Fields
value

value (Value format)

The return value of the expression

count

integer

The number of times that expression returned.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2021-06-30 UTC.