aboutsummaryrefslogtreecommitdiff
path: root/infra/build/functions/test_utils.py
blob: 9aac8eac84b12af4e62588f909f43568e1b667d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Copyright 2020 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
"""Utility functions for testing cloud functions."""
import datetime
import os
import subprocess
import threading

import requests

DATASTORE_READY_INDICATOR = b'is now running'
DATASTORE_EMULATOR_PORT = 8432
EMULATOR_TIMEOUT = 20
TEST_PROJECT_ID = 'test-project'


# pylint: disable=arguments-differ
class SpoofedDatetime(datetime.datetime):
  """Mocking Datetime class for now() function."""

  @classmethod
  def now(cls):
    return datetime.datetime(2020, 1, 1, 0, 0, 0)


def start_datastore_emulator():
  """Start Datastore emulator."""
  return subprocess.Popen([
      'gcloud',
      'beta',
      'emulators',
      'datastore',
      'start',
      '--consistency=1.0',
      '--host-port=localhost:' + str(DATASTORE_EMULATOR_PORT),
      '--project=' + TEST_PROJECT_ID,
      '--no-store-on-disk',
  ],
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)


def wait_for_emulator_ready(proc,
                            emulator,
                            indicator,
                            timeout=EMULATOR_TIMEOUT):
  """Wait for emulator to be ready."""

  def _read_thread(proc, ready_event):
    """Thread to continuously read from the process stdout."""
    ready = False
    while True:
      line = proc.stdout.readline()
      if not line:
        break
      if not ready and indicator in line:
        ready = True
        ready_event.set()

  # Wait for process to become ready.
  ready_event = threading.Event()
  thread = threading.Thread(target=_read_thread, args=(proc, ready_event))
  thread.daemon = True
  thread.start()
  if not ready_event.wait(timeout):
    raise RuntimeError(
        '{} emulator did not get ready in time.'.format(emulator))
  return thread


def reset_ds_emulator():
  """Reset ds emulator/clean all entities."""
  req = requests.post(
      'http://localhost:{}/reset'.format(DATASTORE_EMULATOR_PORT))
  req.raise_for_status()


def cleanup_emulator(ds_emulator):
  """Cleanup the system processes made by ds emulator."""
  del ds_emulator  #To do, find a better way to cleanup emulator
  os.system('pkill -f datastore')


def set_gcp_environment():
  """Set environment variables for simulating in google cloud platform."""
  os.environ['DATASTORE_EMULATOR_HOST'] = 'localhost:' + str(
      DATASTORE_EMULATOR_PORT)
  os.environ['GOOGLE_CLOUD_PROJECT'] = TEST_PROJECT_ID
  os.environ['DATASTORE_DATASET'] = TEST_PROJECT_ID
  os.environ['GCP_PROJECT'] = TEST_PROJECT_ID
  os.environ['FUNCTION_REGION'] = 'us-central1'