feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
Want to contribute? Great! First, read this page (including the small print at the end).
### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
### Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
### The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2016 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.

View File

@@ -0,0 +1,25 @@
Ruby Externalized Runtime
============================
This is the Ruby runtime definition that is used by gcloud to generate
Dockerfiles for GAE.
How to Run Tests
============================
In order to test your runtime changes you will need to run the following
commands.
```
$ sudo apt-get install python-pip
$ sudo pip install virtualenv
$ cd $CODE_DIRECTORY
$ git clone $GIT_HOST/ext-runtime-sdk
$ virtualenv test_env
$ . test_env/bin/activate
(test_env)$ pip install ext-runtime-sdk/
(test_env)$ pip install PyYaml appengine-config-transformer
(test_env)$ cd gae-xrt-ruby
(test_env)$ python test/runtime_test.py
```

View File

@@ -0,0 +1,81 @@
#!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.
# Ruby detection script.
import glob
import json
import os
import sys
# HACK: Import a vendored gae_ext_runtime library until we have a better
# solution.
sys.path.append(os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))), 'lib'))
from gae_ext_runtime import comm
def main(args):
if len(args) != 2:
print 'Invalid Usage: {} <source-root-directory>'.format(args[0])
return 1
directory = args[1]
# The directory is considered a Ruby application if any are true:
# * The top-level directory contains a Gemfile
# * The top-level directory contains a config.ru
# * The top-level directory contains a file ending in .rb
gemfile = os.path.isfile(os.path.join(directory, 'Gemfile'))
configru = os.path.isfile(os.path.join(directory, 'config.ru'))
ruby_file = glob.glob(os.path.join(directory, '*.rb'))
if not gemfile and not configru and not ruby_file:
return 1
try:
with open(os.path.join(directory, '.ruby-version')) as f:
ruby_version = f.read().strip()
except IOError:
ruby_version = ''
config = comm.get_config()
appinfo = config.params.appinfo
if appinfo and appinfo.entrypoint:
entrypoint = appinfo.entrypoint
else:
default = 'bundle exec rackup -p $PORT'
prompt = ('This looks like a Ruby application. Please confirm the '
'command to run as the entrypoint:')
# Currently query_user does not seem to return the default on empty
# response, so do the defaulting ourselves until that is fixed.
entrypoint = comm.query_user(prompt, default) or default
runtime_data = {
'ruby_version': ruby_version,
'entrypoint': entrypoint,
}
appinfo = {
'runtime': 'custom' if config.params.custom else 'ruby',
'env': 'flex',
'entrypoint': entrypoint,
}
comm.send_runtime_params(runtime_data, appinfo=appinfo)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))

View File

@@ -0,0 +1,56 @@
#!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.
import json
import os
import sys
# HACK: Import a vendored gae_ext_runtime library until we have a better
# solution.
sys.path.append(os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))), 'lib'))
from gae_ext_runtime import comm
def main(args):
config = comm.get_config()
params = config.params
if not params.custom and not params.deploy:
return 0
entrypoint = config.runtime_data.entrypoint
ruby_version = config.runtime_data.ruby_version
base_image_tag = os.environ.get('GAE_RUBY_BASE_IMAGE_TAG') or 'latest'
# Locate template directory.
template_dir = os.path.join(os.path.dirname(__file__), '..', 'templates')
# Generate Dockerfile
path = os.path.join(template_dir, 'Dockerfile.template')
with open(path, 'r') as f:
data = f.read()
comm.gen_file('Dockerfile', data.format(ruby_version=ruby_version,
entrypoint=entrypoint, base_image_tag=base_image_tag))
# Generate .dockerignore
path = os.path.join(template_dir, 'dockerignore.template')
with open(path, 'r') as f:
comm.gen_file('.dockerignore', f.read())
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))

View File

@@ -0,0 +1,174 @@
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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.
# Note: this file is part of the sdk-ext-runtime package. It gets copied into
# individual GAE runtime modules so that they can be easily deployed.
import json
import os
import sys
class JSONObject(object):
"""Wrapper for a JSON object.
Presents a JSON object as a python object (where fields are attributes)
instead of a dictionary. Undefined attributes produce a value of None
instead of an AttributeError.
Note that attribute names beginning with an underscore are excluded.
"""
def __getattr__(self, attr):
return None
def to_dict(self):
result = {}
for attr, val in self.__dict__.iteritems():
if not attr.startswith('_'):
result[attr] = _make_serializable(val)
return result
# Alias old style naming so this interoperates with gcloud's appinfo.
ToDict = to_dict
def _make_serializable(obj):
"""Converts objects to serializable form."""
if isinstance(obj, JSONObject):
return obj.to_dict()
else:
return obj
def _write_msg(**message):
"""Write a message to standard output.
Args:
**message: ({str: object, ...}) A JSON message encoded in keyword
arguments.
"""
json.dump(message, sys.stdout, default=_make_serializable)
sys.stdout.write('\n')
sys.stdout.flush()
def error(message, *args):
_write_msg(type='error', message=message % args)
def warn(message, *args):
_write_msg(type='warn', message=message % args)
def info(message, *args):
_write_msg(type='info', message=message % args)
def debug(message, *args):
_write_msg(type='debug', message=message % args)
def print_status(message, *args):
_write_msg(type='print_status', message=message % args)
def send_runtime_params(params, appinfo=None):
"""Send runtime parameters back to the controller.
Args:
params: ({str: object, ...}) Set of runtime parameters. Must be
json-encodable.
appinfo: ({str: object, ...} or None) Contents of the app.yaml file to
be produced by the runtime definition. Required fields may be
added to this by the framework, the only thing an application
needs to provide is the "runtime" field and any additional data
fields.
"""
if appinfo is not None:
_write_msg(type='runtime_parameters', runtime_data=params,
appinfo=appinfo)
else:
_write_msg(type='runtime_parameters', runtime_data=params)
def get_config():
"""Request runtime parameters from the controller.
Returns:
(object) The runtime parameters represented as an object.
"""
_write_msg(type='get_config')
return dict_to_object(json.loads(sys.stdin.readline()))
def dict_to_object(json_dict):
"""Converts a dictionary to a python object.
Converts key-values to attribute-values.
Args:
json_dict: ({str: object, ...})
Returns:
(JSONObject)
"""
obj = JSONObject()
for name, val in json_dict.iteritems():
if isinstance(val, dict):
val = dict_to_object(val)
setattr(obj, name, val)
return obj
class RuntimeDefinitionRoot(object):
"""Abstraction that allows us to access files in the runtime definiton."""
def __init__(self, path):
self.root = path
def read_file(self, *name):
with open(os.path.join(self.root, *name)) as src:
return src.read()
def gen_file(name, contents):
"""Generate the file.
This writes the file to be generated back to the controller.
Args:
name: (str) The UNIX-style relative path of the file.
contents: (str) The complete file contents.
"""
_write_msg(type='gen_file', filename=name, contents=contents)
def query_user(prompt, default=None):
"""Query the user for data.
Args:
prompt: (str) Prompt to display to the user.
default: (str or None) Default value to use if the user doesn't input
anything.
Returns:
(str) Value returned by the user.
"""
kwargs = {}
kwargs['prompt'] = prompt
if default is not None:
kwargs['default'] = default
_write_msg(type='query_user', **kwargs)
return json.loads(sys.stdin.readline())['result']

View File

@@ -0,0 +1,8 @@
author: adamtanner@google.com
name: ruby
description: Official Google Ruby runtime definition.
api_version: 0.2
detect:
python: bin/detect
generate_configs:
python: bin/generate_configs

View File

@@ -0,0 +1,54 @@
# This Dockerfile for a Ruby application was generated by gcloud.
# The base Dockerfile installs:
# * A number of packages needed by the Ruby runtime and by gems
# commonly used in Ruby web apps (such as libsqlite3)
# * A recent version of NodeJS
# * A recent version of the standard Ruby runtime to use by default
# * The bundler gem
FROM gcr.io/google-appengine/ruby:{base_image_tag}
# If your application requires a specific ruby version (compatible with rbenv),
# set it here. Leave blank to use the currently recommended default.
ARG REQUESTED_RUBY_VERSION="{ruby_version}"
# Install any requested ruby if not already preinstalled by the base image.
# Tries installing a prebuilt package first, then falls back to a source build.
RUN if test -n "$REQUESTED_RUBY_VERSION" -a \
! -x /rbenv/versions/$REQUESTED_RUBY_VERSION/bin/ruby; then \
(apt-get update -y \
&& apt-get install -y -q gcp-ruby-$REQUESTED_RUBY_VERSION) \
|| (cd /rbenv/plugins/ruby-build \
&& git pull \
&& rbenv install -s $REQUESTED_RUBY_VERSION) \
&& rbenv global $REQUESTED_RUBY_VERSION \
&& gem install -q --no-rdoc --no-ri bundler --version $BUNDLER_VERSION \
&& apt-get clean \
&& rm -f /var/lib/apt/lists/*_*; \
fi
ENV RBENV_VERSION=${{REQUESTED_RUBY_VERSION:-$RBENV_VERSION}}
# Copy the application files.
COPY . /app/
# Install required gems if Gemfile.lock is present.
RUN if test -f Gemfile.lock; then \
bundle install --deployment --without="development test" \
&& rbenv rehash; \
fi
# Temporary. Will be moved to base image later.
ENV RACK_ENV=production \
RAILS_ENV=production \
RAILS_SERVE_STATIC_FILES=true
# Run asset pipeline if we're in a Rails app.
RUN if test -d app/assets -a -f config/application.rb; then \
bundle exec rake assets:precompile || true; \
fi
# BUG: Reset entrypoint to override base image.
ENTRYPOINT []
# Start application on port $PORT.
CMD {entrypoint}

View File

@@ -0,0 +1,5 @@
.dockerignore
Dockerfile
.git
.hg
.svn

View File

@@ -0,0 +1,462 @@
#!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.
import os
import unittest
from gae_ext_runtime import testutil
RUNTIME_DEF_ROOT = os.path.dirname(os.path.dirname(__file__))
DOCKERFILE_TEXT = '''\
# This Dockerfile for a Ruby application was generated by gcloud.
# The base Dockerfile installs:
# * A number of packages needed by the Ruby runtime and by gems
# commonly used in Ruby web apps (such as libsqlite3)
# * A recent version of NodeJS
# * A recent version of the standard Ruby runtime to use by default
# * The bundler gem
FROM gcr.io/google-appengine/ruby:{base_image_tag}
# If your application requires a specific ruby version (compatible with rbenv),
# set it here. Leave blank to use the currently recommended default.
ARG REQUESTED_RUBY_VERSION="{ruby_version}"
# Install any requested ruby if not already preinstalled by the base image.
# Tries installing a prebuilt package first, then falls back to a source build.
RUN if test -n "$REQUESTED_RUBY_VERSION" -a \\
! -x /rbenv/versions/$REQUESTED_RUBY_VERSION/bin/ruby; then \\
(apt-get update -y \\
&& apt-get install -y -q gcp-ruby-$REQUESTED_RUBY_VERSION) \\
|| (cd /rbenv/plugins/ruby-build \\
&& git pull \\
&& rbenv install -s $REQUESTED_RUBY_VERSION) \\
&& rbenv global $REQUESTED_RUBY_VERSION \\
&& gem install -q --no-rdoc --no-ri bundler --version $BUNDLER_VERSION \\
&& apt-get clean \\
&& rm -f /var/lib/apt/lists/*_*; \\
fi
ENV RBENV_VERSION=${{REQUESTED_RUBY_VERSION:-$RBENV_VERSION}}
# Copy the application files.
COPY . /app/
# Install required gems if Gemfile.lock is present.
RUN if test -f Gemfile.lock; then \\
bundle install --deployment --without="development test" \\
&& rbenv rehash; \\
fi
# Temporary. Will be moved to base image later.
ENV RACK_ENV=production \\
RAILS_ENV=production \\
RAILS_SERVE_STATIC_FILES=true
# Run asset pipeline if we're in a Rails app.
RUN if test -d app/assets -a -f config/application.rb; then \\
bundle exec rake assets:precompile || true; \\
fi
# BUG: Reset entrypoint to override base image.
ENTRYPOINT []
# Start application on port $PORT.
CMD {entrypoint}
'''
class RuntimeTestCase(testutil.TestBase):
"""Tests for the Ruby external runtime fingerprinter."""
def file_contents(self, filename):
"""Reads the contents of the file from the tempdir.
Args:
filename: (str) filename to be joined with tempdir prefix.
Returns:
File contents.
"""
with open(self.full_path(filename)) as f:
return f.read()
def stub_response(self, response):
"""Stubs the console response from the user.
Args:
response: (str) stubbed response.
Returns:
A function to reset the stubbed functions to their original
implementations.
"""
can_prompt = self.exec_env.CanPrompt
prompt_response = self.exec_env.PromptResponse
def unstub():
self.exec_env.CanPrompt = can_prompt
self.exec_env.PromptResponse = prompt_response
self.exec_env.CanPrompt = lambda: True
self.exec_env.PromptResponse = lambda prompt: response
return unstub
def setUp(self):
self.runtime_def_root = RUNTIME_DEF_ROOT
super(RuntimeTestCase, self).setUp()
def test_generate_without_ruby_files(self):
self.write_file('index.html', 'index')
self.generate_configs()
self.assertFalse(os.path.exists(self.full_path('app.yaml')))
self.assertFalse(os.path.exists(self.full_path('Dockerfile')))
self.assertFalse(os.path.exists(self.full_path('.dockerignore')))
def test_generate_without_ruby_files_no_write(self):
"""Tests generate_config_data does nothing if no ruby files."""
self.write_file('index.html', 'index')
self.assertIsNone(self.generate_config_data())
self.assertFalse(os.path.exists(self.full_path('app.yaml')))
def test_generate_with_ruby_files(self):
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
unstub = self.stub_response('bundle exec rackup -p $PORT -E deployment')
self.generate_configs()
unstub()
app_yaml = self.file_contents('app.yaml')
self.assertIn('runtime: ruby\n', app_yaml)
self.assertIn('env: flex\n', app_yaml)
self.assertIn('entrypoint: bundle exec rackup -p $PORT -E deployment\n',
app_yaml)
self.assertFalse(os.path.exists(self.full_path('Dockerfile')))
self.assertFalse(os.path.exists(self.full_path('.dockerignore')))
def test_generate_with_ruby_files_no_write(self):
"""Tests generate_config_data with basic Ruby files.
Tests that app.yaml is written with correct contents given entrypoint
response, and that Dockerfile and .dockerignore not written to disk.
"""
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
unstub = self.stub_response('bundle exec rackup -p $PORT -E deployment')
cfg_files = self.generate_config_data()
unstub()
app_yaml = self.file_contents('app.yaml')
self.assertIn('runtime: ruby\n', app_yaml)
self.assertIn('env: flex\n', app_yaml)
self.assertIn('entrypoint: bundle exec rackup -p $PORT -E deployment\n',
app_yaml)
self.assertNotIn('Dockerfile', [f.filename for f in cfg_files])
self.assertNotIn('.dockerignore', [f.filename for f in cfg_files])
def test_generate_with_deploy(self):
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
self.write_file('.ruby-version', 'rbx-3.9')
unstub = self.stub_response('bundle exec rackup -p $PORT -E deployment')
self.generate_configs(deploy=True)
unstub()
dockerfile = self.file_contents('Dockerfile')
self.assertEqual(
dockerfile,
DOCKERFILE_TEXT.format(
ruby_version='rbx-3.9',
entrypoint='bundle exec rackup -p $PORT -E deployment'))
dockerignore = self.file_contents('.dockerignore')
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_deploy_no_write(self):
"""Tests generate_config_data with deploy=True.
Tests that .dockerignore and Dockerfile contents are correct
based on contents of app.
"""
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
self.write_file('.ruby-version', 'rbx-3.9')
unstub = self.stub_response('bundle exec rackup -p $PORT -E deployment')
cfg_files = self.generate_config_data(deploy=True)
unstub()
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
DOCKERFILE_TEXT.format(
ruby_version='rbx-3.9',
entrypoint='bundle exec rackup -p $PORT -E deployment'))
self.assertIn('.dockerignore', [f.filename for f in cfg_files])
dockerignore = [f.contents for f in cfg_files if
f.filename == '.dockerignore'][0]
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_custom(self):
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
unstub = self.stub_response('bundle exec rackup -p $PORT -E deployment')
self.generate_configs(custom=True)
unstub()
app_yaml = self.file_contents('app.yaml')
self.assertIn('runtime: custom\n', app_yaml)
self.assertIn('env: flex\n', app_yaml)
self.assertIn('entrypoint: bundle exec rackup -p $PORT -E deployment\n',
app_yaml)
dockerfile = self.file_contents('Dockerfile')
self.assertEqual(
dockerfile,
DOCKERFILE_TEXT.format(
ruby_version='',
entrypoint='bundle exec rackup -p $PORT -E deployment'))
dockerignore = self.file_contents('.dockerignore')
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_custom_no_write(self):
"""Tests generate_config_data with custom=True.
Tests that app.yaml is written with correct parameters and
Dockerfile, .dockerignore contents are correctly returned by method.
"""
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
unstub = self.stub_response('bundle exec rackup -p $PORT -E deployment')
cfg_files = self.generate_config_data(custom=True)
unstub()
app_yaml = self.file_contents('app.yaml')
self.assertIn('runtime: custom\n', app_yaml)
self.assertIn('env: flex\n', app_yaml)
self.assertIn('entrypoint: bundle exec rackup -p $PORT -E deployment\n',
app_yaml)
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
DOCKERFILE_TEXT.format(
ruby_version='',
entrypoint='bundle exec rackup -p $PORT -E deployment'))
self.assertIn('.dockerignore', [f.filename for f in cfg_files])
dockerignore = [f.contents for f in cfg_files if
f.filename == '.dockerignore'][0]
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_existing_appinfo(self):
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
appinfo = testutil.AppInfoFake(
entrypoint='bundle exec ruby index.rb $PORT',
runtime='ruby',
vm=True)
self.generate_configs(appinfo=appinfo, deploy=True)
self.assertFalse(os.path.exists(self.full_path('app.yaml')))
dockerfile = self.file_contents('Dockerfile')
self.assertEqual(
dockerfile,
DOCKERFILE_TEXT.format(
ruby_version='',
entrypoint='bundle exec ruby index.rb $PORT'))
dockerignore = self.file_contents('.dockerignore')
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_existing_appinfo_no_write(self):
"""Tests generate_config_data with passed appinfo."""
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
appinfo = testutil.AppInfoFake(
entrypoint='bundle exec ruby index.rb $PORT',
runtime='ruby',
vm=True)
cfg_files = self.generate_config_data(appinfo=appinfo, deploy=True)
self.assertFalse(os.path.exists(self.full_path('app.yaml')))
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
DOCKERFILE_TEXT.format(
ruby_version='',
entrypoint='bundle exec ruby index.rb $PORT'))
self.assertIn('.dockerignore', [f.filename for f in cfg_files])
dockerignore = [f.contents for f in cfg_files if
f.filename == '.dockerignore'][0]
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_ruby_version(self):
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
self.write_file('.ruby-version', '2.3.1\n')
appinfo = testutil.AppInfoFake(
entrypoint='bundle exec ruby index.rb $PORT',
runtime='ruby',
vm=True)
self.generate_configs(appinfo=appinfo, deploy=True)
self.assertFalse(os.path.exists(self.full_path('app.yaml')))
dockerfile = self.file_contents('Dockerfile')
self.assertEqual(
dockerfile,
DOCKERFILE_TEXT.format(
ruby_version='2.3.1',
entrypoint='bundle exec ruby index.rb $PORT'))
dockerignore = self.file_contents('.dockerignore')
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_ruby_version_no_write(self):
"""Tests generate_config_data with .ruby-version file."""
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
self.write_file('config.ru', 'run Index.app')
self.write_file('.ruby-version', '2.3.1\n')
appinfo = testutil.AppInfoFake(
entrypoint='bundle exec ruby index.rb $PORT',
runtime='ruby',
vm=True)
cfg_files = self.generate_config_data(appinfo=appinfo, deploy=True)
self.assertFalse(os.path.exists(self.full_path('app.yaml')))
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
DOCKERFILE_TEXT.format(
ruby_version='2.3.1',
entrypoint='bundle exec ruby index.rb $PORT'))
self.assertIn('.dockerignore', [f.filename for f in cfg_files])
dockerignore = [f.contents for f in cfg_files if
f.filename == '.dockerignore'][0]
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_prompt(self):
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
unstub = self.stub_response('bundle exec ruby index.rb $PORT')
self.generate_configs(deploy=True)
unstub()
dockerfile = self.file_contents('Dockerfile')
self.assertEqual(
dockerfile,
DOCKERFILE_TEXT.format(
ruby_version='',
entrypoint='bundle exec ruby index.rb $PORT'))
dockerignore = self.file_contents('.dockerignore')
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
def test_generate_with_prompt_no_write(self):
"""Tests generate_config_data with entrypoint given by prompt."""
self.write_file('index.rb', 'class Index; end')
self.write_file('Gemfile', 'source "https://rubygems.org"')
unstub = self.stub_response('bundle exec ruby index.rb $PORT')
cfg_files = self.generate_config_data(deploy=True)
unstub()
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
DOCKERFILE_TEXT.format(
ruby_version='',
entrypoint='bundle exec ruby index.rb $PORT'))
self.assertIn('.dockerignore', [f.filename for f in cfg_files])
dockerignore = [f.contents for f in cfg_files if
f.filename == '.dockerignore'][0]
self.assertIn('.dockerignore\n', dockerignore)
self.assertIn('Dockerfile\n', dockerignore)
self.assertIn('.git\n', dockerignore)
self.assertIn('.hg\n', dockerignore)
self.assertIn('.svn\n', dockerignore)
if __name__ == '__main__':
unittest.main()