使用模拟器测试Firestore规则时如何设置测试数据?

时间:2019-05-23 04:30:19

标签: firebase google-cloud-firestore firebase-security-rules firebase-cli

我正在使用mocha和Firestore 仿真器进行Cloud Firestore规则的测试,问题是如何在运行测试之前初始化一些测试数据?

要测试我的规则,我首先需要初始化一些测试数据。问题是在使用仿真器时,我无法将任何数据放入文档中,文档仅包含id。 我没有在the docs中找到任何为Rules测试设置测试数据的示例,因此我尝试同时使用 makeDocumentSnapshot中的@firebase/testing,并通过使用initializeAdminApp创建的管理应用创建文档。

用例

要访问/objects/{object_id}上的文档,必须认证用户并拥有read权限:get('/objects/{object_id}/users/{$(request.auth.uid)}').data.read == true。另外,object必须可用:get('/objects/{object_id}').data.available == true

因此,要测试我的规则,我需要一些具有用户权限的预设测试数据。

预期的数据库结构

objects collection:
  object_id: {
    // document fields:
    available (bool)

    // nested collection:
    users collection: {
      user_id: {
        // document fields:
        read (bool)
      }
    }
  }

我的规则示例

service cloud.firestore {
  match /databases/{database}/documents {
    match /objects/{object} {
      function objectAvailable() {
        return resource.data.available;
      }
      // User has read access.
      function userCanReadObject() {
        return get(/databases/$(database)/documents/objects/$(object)/users/$(request.auth.uid)).data.read == true;
      }
      // Objects Permission Rules
      allow read: if objectAvailable() && userCanReadObject();
      allow write: if false;

      // Access forbidden. Used for permission rules only.
      match /users/{document=**} {
        allow read, write: if false;
      }
    }
  }
}

我的测试示例

const firebase = require('@firebase/testing');
const fs = require('fs');

// Load Firestore rules from file
const firestoreRules = fs.readFileSync('../firestore.rules', 'utf8');
const projectId = 'test-application';
const test = require('firebase-functions-test')({ projectId, databaseName: projectId });

describe('Tests for Rules', () => {
  let adminApp;

  const testData = {
    myObj: {
      id: 'test',
      data: {
        available: true,
      },
    },
    alice: {
      id: 1,
      data: {
        read: true,
      },
    },
  };

  before(async () => {
    // Load Rules
    await firebase.loadFirestoreRules({ projectId,  rules: firestoreRules });

    // Initialize admin app.
    adminApp = firebase.initializeAdminApp({ projectId }).firestore();

    // Create test data
    await adminApp.doc(`objects/${testData.myObj.id}`).set(testData.myObj.data);
    await adminApp
      .doc(`objects/${testData.myObj.id}/users/${testData.alice.id}`)
      .set(testData.alice.data);

    // Create test data with  `firebase-functions-test`
    // test.firestore.makeDocumentSnapshot(testData.myObj.data, `objects/${testData.myObj.id}`);
    // test.firestore.makeDocumentSnapshot(
    //   testData.alice.data,
    //   `objects/${testData.myObj.id}/users/${testData.alice.id}`,
    // );
  });

  beforeEach(async () => {
    await firebase.clearFirestoreData({ projectId });
  });

  after(async () => {
    // Shut down all testing Firestore applications after testing is done.
    await Promise.all(firebase.apps().map(app => app.delete()));
  });

  describe('Testing', () => {
    it('User with permission can read objects data', async () => {
      const db = firebase
        .initializeTestApp({ projectId, auth: { uid: testData.alice.id } })
        .firestore();
      const testObj = db.doc(`objects/${testData.myObj.id}`);

      await firebase.assertSucceeds(testObj.get());
    });
  });
});

控制台输出以进行测试运行:

1) User with permission can read objects data
0 passing (206ms)
1 failing
1) Tests for Rules
 Testing
   User with permission can read objects data:
FirebaseError: 
false for 'get' @ L53

要检查创建的测试数据,我在await firebase.assertSucceeds(testObj.get());行之前添加了以下代码:

const o = await adminApp.doc(`objects/${testData.myObj.id}`).get();
const u = await adminApp.doc(`objects/${testData.myObj.id}/users/${testData.alice.id}`).get();
console.log('obj data: ', o.id, o.data());
console.log('user data: ', u.id, u.data());

输出如下:

obj data:  test undefined
user data:  1 undefined

我还尝试从beforeEach删除代码,结果是相同的。

2 个答案:

答案 0 :(得分:4)

您可以使用<security:authentication property="principal.firstName"/>来获得管理员特权(允许所有操作):

initializeAdminApp

数据应该具有以下格式:


    const dbAdmin = firebase.initializeAdminApp({projectId}).firestore();

    // Write mock documents
    if (data) {
        for (const key in data) {
            if (data.hasOwnProperty(key)) {
                const ref = dbAdmin.doc(key);
                await ref.set(data[key]);
            }
        }
    }

答案 1 :(得分:0)

在应用规则之前,您必须添加数据。

您可以找到here

的详细信息
const firebase = require('@firebase/testing');
const fs = require('fs');
let db
let projectId = `my-project-id-${Date.now()}`

async function setup(auth) {
  const app = await firebase.initializeTestApp({
    projectId: projectId,
    auth: auth
  });

  db = app.firestore();

  let data = {
    'users/alovelace': {
      first: 'Ada',
      last: 'Lovelace'
    }
  }

  // Add data before apply rules
  for (const key in data) {
    const ref = db.doc(key);
    await ref.set(data[key]);
  }

  // Apply rules
  await firebase.loadFirestoreRules({
    projectId,
    rules: fs.readFileSync('firestore.rules', 'utf8')
  });
}

test('logged in', async () => {
  await setup({ uid: "alovelace" })

  let docRef = db.collection('users');

  // check if there is data
  let users = await docRef.get()
  users.forEach(user => {
  console.warn(user.id, user.data())
  });

  let read = await firebase.assertSucceeds(docRef.get());
  let write = await firebase.assertFails(docRef.add({}));

  await expect(read)
  await expect(write)
});

afterAll(async () => {
  Promise.all(firebase.apps().map(app => app.delete()))
});

firestore.rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
       allow read:if request.auth.uid != null;
       allow write: if false
    }
  }
}