aboutsummaryrefslogtreecommitdiff
path: root/infra/build/functions/project_sync_test.py
blob: f90733810037b47a89e5f78fc8a955219c99ee8a (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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# 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.
#
################################################################################
"""Unit tests for Cloud Function sync, which syncs the list of github projects
and uploads them to the Cloud Datastore."""

import os
import sys
import unittest

from google.cloud import ndb

sys.path.append(os.path.dirname(__file__))
# pylint: disable=wrong-import-position

from datastore_entities import Project
from project_sync import get_github_creds
from project_sync import get_projects
from project_sync import ProjectMetadata
from project_sync import sync_projects
import test_utils

# pylint: disable=no-member


# pylint: disable=too-few-public-methods
class Repository:
  """Mocking Github Repository."""

  def __init__(self, name, file_type, path, contents=None):
    self.contents = contents or []
    self.name = name
    self.type = file_type
    self.path = path
    self.decoded_content = b"name: test"

  def get_contents(self, path):
    """"Get contents of repository."""
    if self.path == path:
      return self.contents

    for content_file in self.contents:
      if content_file.path == path:
        return content_file.contents

    return None

  def set_yaml_contents(self, decoded_content):
    """Set yaml_contents."""
    self.decoded_content = decoded_content


class CloudSchedulerClient:
  """Mocking cloud scheduler client."""

  def __init__(self):
    self.schedulers = []

  # pylint: disable=no-self-use
  def location_path(self, project_id, location_id):
    """Return project path."""
    return 'projects/{}/location/{}'.format(project_id, location_id)

  def create_job(self, parent, job):
    """Simulate create job."""
    del parent
    self.schedulers.append(job)

  # pylint: disable=no-self-use
  def job_path(self, project_id, location_id, name):
    """Return job path."""
    return 'projects/{}/location/{}/jobs/{}'.format(project_id, location_id,
                                                    name)

  def delete_job(self, name):
    """Simulate delete jobs."""
    for job in self.schedulers:
      if job['name'] == name:
        self.schedulers.remove(job)
        break

  def update_job(self, job, update_mask):
    """Simulate update jobs."""
    for existing_job in self.schedulers:
      if existing_job == job:
        job['schedule'] = update_mask['schedule']


class TestDataSync(unittest.TestCase):
  """Unit tests for sync."""

  @classmethod
  def setUpClass(cls):
    cls.ds_emulator = test_utils.start_datastore_emulator()
    test_utils.wait_for_emulator_ready(cls.ds_emulator, 'datastore',
                                       test_utils.DATASTORE_READY_INDICATOR)
    test_utils.set_gcp_environment()

  def setUp(self):
    test_utils.reset_ds_emulator()

  def test_sync_projects_update(self):
    """Testing sync_projects() updating a schedule."""
    cloud_scheduler_client = CloudSchedulerClient()

    with ndb.Client().context():
      Project(name='test1',
              schedule='0 8 * * *',
              project_yaml_contents='',
              dockerfile_contents='').put()
      Project(name='test2',
              schedule='0 9 * * *',
              project_yaml_contents='',
              dockerfile_contents='').put()

      projects = {
          'test1': ProjectMetadata('0 8 * * *', '', ''),
          'test2': ProjectMetadata('0 7 * * *', '', '')
      }
      sync_projects(cloud_scheduler_client, projects)

      projects_query = Project.query()
      self.assertEqual({
          'test1': '0 8 * * *',
          'test2': '0 7 * * *'
      }, {project.name: project.schedule for project in projects_query})

  def test_sync_projects_create(self):
    """"Testing sync_projects() creating new schedule."""
    cloud_scheduler_client = CloudSchedulerClient()

    with ndb.Client().context():
      Project(name='test1',
              schedule='0 8 * * *',
              project_yaml_contents='',
              dockerfile_contents='').put()

      projects = {
          'test1': ProjectMetadata('0 8 * * *', '', ''),
          'test2': ProjectMetadata('0 7 * * *', '', '')
      }
      sync_projects(cloud_scheduler_client, projects)

      projects_query = Project.query()
      self.assertEqual({
          'test1': '0 8 * * *',
          'test2': '0 7 * * *'
      }, {project.name: project.schedule for project in projects_query})

      self.assertCountEqual([
          {
              'name': 'projects/test-project/location/us-central1/jobs/'
                      'test2-scheduler-fuzzing',
              'pubsub_target': {
                  'topic_name': 'projects/test-project/topics/request-build',
                  'data': b'test2'
              },
              'schedule': '0 7 * * *'
          },
          {
              'name': 'projects/test-project/location/us-central1/jobs/'
                      'test2-scheduler-coverage',
              'pubsub_target': {
                  'topic_name':
                      'projects/test-project/topics/request-coverage-build',
                  'data':
                      b'test2'
              },
              'schedule': '0 6 * * *'
          },
      ], cloud_scheduler_client.schedulers)

  def test_sync_projects_delete(self):
    """Testing sync_projects() deleting."""
    cloud_scheduler_client = CloudSchedulerClient()

    with ndb.Client().context():
      Project(name='test1',
              schedule='0 8 * * *',
              project_yaml_contents='',
              dockerfile_contents='').put()
      Project(name='test2',
              schedule='0 9 * * *',
              project_yaml_contents='',
              dockerfile_contents='').put()

      projects = {'test1': ProjectMetadata('0 8 * * *', '', '')}
      sync_projects(cloud_scheduler_client, projects)

      projects_query = Project.query()
      self.assertEqual(
          {'test1': '0 8 * * *'},
          {project.name: project.schedule for project in projects_query})

  def test_get_projects_yaml(self):
    """Testing get_projects() yaml get_schedule()."""

    repo = Repository('oss-fuzz', 'dir', 'projects', [
        Repository('test0', 'dir', 'projects/test0', [
            Repository('Dockerfile', 'file', 'projects/test0/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ]),
        Repository('test1', 'dir', 'projects/test1', [
            Repository('Dockerfile', 'file', 'projects/test1/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test1/project.yaml')
        ])
    ])
    repo.contents[0].contents[1].set_yaml_contents(b'builds_per_day: 2')
    repo.contents[1].contents[1].set_yaml_contents(b'builds_per_day: 3')

    self.assertEqual(
        get_projects(repo), {
            'test0':
                ProjectMetadata('0 6,18 * * *', 'builds_per_day: 2',
                                'name: test'),
            'test1':
                ProjectMetadata('0 6,14,22 * * *', 'builds_per_day: 3',
                                'name: test')
        })

  def test_get_projects_no_docker_file(self):
    """Testing get_projects() with missing dockerfile"""

    repo = Repository('oss-fuzz', 'dir', 'projects', [
        Repository('test0', 'dir', 'projects/test0', [
            Repository('Dockerfile', 'file', 'projects/test0/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ]),
        Repository('test1', 'dir', 'projects/test1')
    ])

    self.assertEqual(
        get_projects(repo),
        {'test0': ProjectMetadata('0 6 * * *', 'name: test', 'name: test')})

  def test_get_projects_invalid_project_name(self):
    """Testing get_projects() with invalid project name"""

    repo = Repository('oss-fuzz', 'dir', 'projects', [
        Repository('test0', 'dir', 'projects/test0', [
            Repository('Dockerfile', 'file', 'projects/test0/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ]),
        Repository('test1@', 'dir', 'projects/test1', [
            Repository('Dockerfile', 'file', 'projects/test1/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ])
    ])

    self.assertEqual(
        get_projects(repo),
        {'test0': ProjectMetadata('0 6 * * *', 'name: test', 'name: test')})

  def test_get_projects_non_directory_type_project(self):
    """Testing get_projects() when a file in projects/ is not of type 'dir'."""

    repo = Repository('oss-fuzz', 'dir', 'projects', [
        Repository('test0', 'dir', 'projects/test0', [
            Repository('Dockerfile', 'file', 'projects/test0/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ]),
        Repository('test1', 'file', 'projects/test1')
    ])

    self.assertEqual(
        get_projects(repo),
        {'test0': ProjectMetadata('0 6 * * *', 'name: test', 'name: test')})

  def test_invalid_yaml_format(self):
    """Testing invalid yaml schedule parameter argument."""

    repo = Repository('oss-fuzz', 'dir', 'projects', [
        Repository('test0', 'dir', 'projects/test0', [
            Repository('Dockerfile', 'file', 'projects/test0/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ])
    ])
    repo.contents[0].contents[1].set_yaml_contents(
        b'builds_per_day: some-string')

    self.assertEqual(get_projects(repo), {})

  def test_yaml_out_of_range(self):
    """Testing invalid yaml schedule parameter argument."""

    repo = Repository('oss-fuzz', 'dir', 'projects', [
        Repository('test0', 'dir', 'projects/test0', [
            Repository('Dockerfile', 'file', 'projects/test0/Dockerfile'),
            Repository('project.yaml', 'file', 'projects/test0/project.yaml')
        ])
    ])
    repo.contents[0].contents[1].set_yaml_contents(b'builds_per_day: 5')

    self.assertEqual(get_projects(repo), {})

  def test_get_github_creds(self):
    """Testing get_github_creds()."""
    with ndb.Client().context():
      self.assertRaises(RuntimeError, get_github_creds)

  @classmethod
  def tearDownClass(cls):
    test_utils.cleanup_emulator(cls.ds_emulator)


if __name__ == '__main__':
  unittest.main(exit=False)