aboutsummaryrefslogtreecommitdiff
path: root/infra/build/functions/test_utils.py
blob: a093bcfa07cff08e81e1459809b7f40cb4af65db (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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# 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

FUNCTIONS_DIR = os.path.dirname(__file__)
OSS_FUZZ_DIR = os.path.dirname(os.path.dirname(os.path.dirname(FUNCTIONS_DIR)))
PROJECTS_DIR = os.path.join(OSS_FUZZ_DIR, 'projects')

FAKE_DATETIME = datetime.datetime(2020, 1, 1, 0, 0, 0)
IMAGE_PROJECT = 'oss-fuzz'
BASE_IMAGES_PROJECT = 'oss-fuzz-base'
PROJECT = 'test-project'
PROJECT_DIR = os.path.join(PROJECTS_DIR, PROJECT)


def create_project_data(project,
                        project_yaml_contents,
                        dockerfile_contents='test line'):
  """Creates a project.yaml with |project_yaml_contents| and a Dockerfile with
  |dockerfile_contents| for |project|."""
  project_dir = os.path.join(PROJECTS_DIR, project)
  project_yaml_path = os.path.join(project_dir, 'project.yaml')
  with open(project_yaml_path, 'w') as project_yaml_handle:
    project_yaml_handle.write(project_yaml_contents)

  dockerfile_path = os.path.join(project_dir, 'Dockerfile')
  with open(dockerfile_path, 'w') as dockerfile_handle:
    dockerfile_handle.write(dockerfile_contents)


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=' + PROJECT,
      '--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(f'{emulator} emulator did not get ready in time.')
  return thread


def reset_ds_emulator():
  """Reset ds emulator/clean all entities."""
  req = requests.post(f'http://localhost:{DATASTORE_EMULATOR_PORT}/reset')
  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'] = PROJECT
  os.environ['DATASTORE_DATASET'] = PROJECT
  os.environ['GCP_PROJECT'] = PROJECT
  os.environ['FUNCTION_REGION'] = 'us-central1'


def get_test_data_file_path(filename):
  """Returns the path to a test data file with name |filename|."""
  return os.path.join(os.path.dirname(__file__), 'test_data', filename)