В состав Firebase CLI входит эмулятор Cloud Functions , который может эмулировать следующие типы функций:
- функции HTTPS
- Вызываемые функции
- Функции очереди задач
- Фоновые функции запускаются из Firebase Authentication , Realtime Database , Cloud Firestore , Cloud Storage , поддерживаемых оповещений Firebase и Cloud Pub/Sub.
Вы можете запускать функции локально, чтобы протестировать их перед развертыванием в рабочей среде.
Установите Firebase CLI.
Для использования эмулятора Cloud Functions сначала установите Firebase CLI:
npm install -g firebase-tools
Для использования локального эмулятора ваши Cloud Functions должны зависеть от следующих компонентов:
-
firebase-adminверсии8.0.0или выше. -
firebase-functionsверсии3.0.0или выше.
Настройка учетных данных администратора (необязательно)
Если вы хотите, чтобы ваши функциональные тесты взаимодействовали с API Google или другими API Firebase через Firebase Admin SDK , вам может потребоваться настроить учетные данные администратора.
- Триггеры Cloud Firestore и Realtime Database уже имеют достаточные учетные данные и не требуют дополнительной настройки.
- All other APIs, including Firebase APIs such as Authentication and FCM or Google APIs such as Cloud Translation or Cloud Speech, require the setup steps described in this section. This applies whether you're using the Cloud Functions shell or
firebase emulators:start.
Для настройки учетных данных администратора для эмулируемых функций:
- Откройте панель «Учетные записи служб» в консоли Google Cloud .
- Убедитесь, что выбрана учетная запись службы App Engine по умолчанию , и воспользуйтесь меню параметров справа, чтобы выбрать «Создать ключ» .
- При появлении запроса выберите JSON в качестве типа ключа и нажмите «Создать» .
Настройте учетные данные Google по умолчанию так, чтобы они указывали на загруженный ключ:
Unix
export GOOGLE_APPLICATION_CREDENTIALS="path/to/key.json" firebase emulators:start
Windows
set GOOGLE_APPLICATION_CREDENTIALS=path\to\key.json firebase emulators:start
After completing these steps, your functions tests can access Firebase and Google APIs using the Admin SDK . For example, when testing an Authentication trigger, the emulated function could call admin.auth().getUserByEmail(email) .
Настройка конфигурации функций (необязательно)
Если вы используете пользовательские переменные конфигурации функций, сначала выполните команду для получения вашей пользовательской конфигурации (выполните её в каталоге functions ) в вашей локальной среде:
firebase functions:config:get > .runtimeconfig.json # If using Windows PowerShell, replace the above with: # firebase functions:config:get | ac .runtimeconfig.json
Запустите набор эмуляторов.
Для запуска эмулятора Cloud Functions используйте команду emulators:start :
firebase emulators:start
The emulators:start command will start emulators for Cloud Functions , Cloud Firestore, Realtime Database, and Firebase Hosting based on the products you have initialized in your local project using firebase init . If you want to start a particular emulator, use the --only flag:
firebase emulators:start --only functions
Если вы хотите запустить набор тестов или скрипт тестирования после запуска эмуляторов, используйте команду emulators:exec :
firebase emulators:exec "./my-test.sh"
After startup, the emulator streams logs from your functions to the terminal window where it runs. It displays all output from console.log() , console.info() , console.error() , and console.warn() statements inside your functions.
Note that emulator output simulates deployment of functions by default in a specific region ( us-central1 ) that may not match the actual production deployment default region. See Cloud Functions locations for more information about regions.
Настройте ваше приложение для взаимодействия с эмуляторами.
Для обеспечения взаимодействия вашего приложения с эмуляторами может потребоваться дополнительная настройка.
Обеспечьте наличие вызываемых функций в вашем приложении.
Если в процессе создания прототипа и тестирования используются вызываемые функции бэкэнда , настройте взаимодействие с эмулятором Cloud Functions for Firebase следующим образом:
Kotlin
// 10.0.2.2 is the special IP address to connect to the 'localhost' of // the host computer from an Android emulator. val functions = Firebase.functions functions.useEmulator("10.0.2.2", 5001)
Java
// 10.0.2.2 is the special IP address to connect to the 'localhost' of // the host computer from an Android emulator. FirebaseFunctions functions = FirebaseFunctions.getInstance(); functions.useEmulator("10.0.2.2", 5001);
Быстрый
Functions.functions().useEmulator(withHost: "localhost", port: 5001)
Единство
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance; // Connects to the Functions Emulator running on port 5001 functions.UseFunctionsEmulator("http://127.0.0.1:5001");
Web
import { getApp } from "firebase/app"; import { getFunctions, connectFunctionsEmulator } from "firebase/functions"; const functions = getFunctions(getApp()); connectFunctionsEmulator(functions, "127.0.0.1", 5001);
Web
firebase.functions().useEmulator("127.0.0.1", 5001);
Добавьте в ваше приложение инструменты для эмуляции функций HTTPS.
Каждая функция HTTPS в вашем коде будет обслуживаться локальным эмулятором с использованием следующего формата URL:
http:// $HOST : $PORT / $PROJECT / $REGION / $NAME
Например, простая функция helloWorld с портом и регионом хоста по умолчанию будет доступна по адресу:
https://localhost:5001/ $PROJECT /us-central1/helloWorld
Оптимизируйте ваше приложение для эмуляции функций очереди задач.
The emulator automatically sets up emulated task queues based on trigger definitions, and the Admin SDK reroutes enqueued requests to the emulator if it detects that it is running via the CLOUD_TASKS_EMULATOR_HOST environment variable.
Note that the dispatch system used in production is more complex than the one implemented in the emulator, so you should not expect emulated behavior to precisely mirror production environments. The parameters within the emulator provide upper bounds to the rate at which tasks get dispatched and retried.
Оптимизируйте ваше приложение для эмуляции функций, запускаемых в фоновом режиме.
Эмулятор Cloud Functions поддерживает функции, запускаемые в фоновом режиме из следующих источников:
- Эмулятор Realtime Database
- Эмулятор Cloud Firestore
- Эмулятор Authentication
- Эмулятор Pub/Sub
- Эмулятор оповещений Firebase
Для запуска фоновых событий изменяйте ресурсы бэкэнда с помощью Emulator Suite UI или подключите ваше приложение или тестовый код к эмуляторам, используя SDK для вашей платформы.
Тестовые обработчики для пользовательских событий, генерируемых расширениями.
Для функций, которые вы реализуете для обработки пользовательских событий Firebase Extensions с помощью Cloud Functions v2, эмулятор Cloud Functions работает в паре с эмулятором Eventarc для поддержки триггеров Eventarc .
Для тестирования пользовательских обработчиков событий для расширений, генерирующих события, необходимо установить эмуляторы Cloud Functions и Eventarc.
The Cloud Functions runtime sets the EVENTARC_EMULATOR environment variable to localhost:9299 in the current process if the Eventarc emulator is running. The Firebase Admin SDK s automatically connect to the Eventarc emulator when the EVENTARC_EMULATOR environment variable is set. You can modify the default port as discussed under Configure Local Emulator Suite .
When environment variables are properly configured, the Firebase Admin SDK automatically sends events to the Eventarc emulator. In turn, the Eventarc emulator makes a call back to the Cloud Functions emulator to trigger any registered handlers.
Подробную информацию о выполнении обработчиков можно посмотреть в журналах функций в Emulator Suite UI .
Взаимодействие с другими сервисами
В состав пакета эмуляторов входит несколько эмуляторов, позволяющих тестировать взаимодействия между различными продуктами.
Cloud Firestore
If you have functions that use the Firebase Admin SDK to write to Cloud Firestore , these writes will be sent to the Cloud Firestore emulator if it is running. If further functions are triggered by those writes, they will be run in the Cloud Functions emulator.
Cloud Storage
If you have functions that use the Firebase Admin SDK (version 9.7.0 or greater) to write to Cloud Storage , these writes will be sent to the Cloud Storage emulator if it is running. If further functions are triggered by those writes, they will be run in the Cloud Functions emulator.
Firebase Authentication
If you have functions that use the Firebase Admin SDK (version 9.3.0 or greater) to write to Firebase Authentication , these writes will be sent to the Auth emulator if it is running. If further functions are triggered by those writes, they will be run in the Cloud Functions emulator.
Хостинг Firebase
Если вы используете Cloud Functions для генерации динамического контента для Firebase Hosting , firebase emulators:start использует ваши локальные HTTP-функции в качестве прокси для хостинга.
Оповещения Firebase
В любом проекте, включающем хотя бы один поддерживаемый триггер оповещений Firebase, пользовательский интерфейс эмулятора содержит вкладку FireAlerts . Для эмуляции триггера оповещений:
- Open the FireAlerts tab. This tab displays a dropdown populated with the alert types that have triggers associated with them (for example, if you have an onNewFatalIssuePublished trigger, then crashlytics.newFatalIssue is displayed).
- Select an alert type. The form auto populates with default values, which can be edited. You can edit the fields of the event (other information from the alert event is either inferred, mock values, or randomly generated).
- Выберите «Отправить оповещение» , чтобы отправить синтетическое оповещение в эмулятор функций, при этом ведение журнала будет доступно в разделе «Оповещения» в консоли Firebase (а также в разделе «Журналы»).
Следующие шаги
Полный пример использования набора инструментов эмулятора Firebase см. в примере быстрого запуска тестирования .