jiebi/CodeConvo huggingface dataset:
<del> #!/bin/bash # Copyright 2014 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. # Launches a container and verifies it can be reached. Assumes that # we're being called by hack/e2e-test.sh (we use some env vars it sets up). set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname "${BASH_SOURCE}")/../.. : ${KUBE_VERSION_ROOT:=${KUBE_ROOT}} : ${KUBECTL:="${KUBE_VERSION_ROOT}/cluster/kubectl.sh"} : ${KUBE_CONFIG_FILE:="config-test.sh"} export KUBECTL KUBE_CONFIG_FILE source "${KUBE_ROOT}/cluster/kube-env.sh" source "${KUBE_VERSION_ROOT}/cluster/${KUBERNETES_PROVIDER}/util.sh" prepare-e2e if [[ "${KUBERNETES_PROVIDER}" != "gce" ]] && [[ "${KUBERNETES_PROVIDER}" != "gke" ]]; then echo "WARNING: Skipping certs.sh for cloud provider: ${KUBERNETES_PROVIDER}." exit 0 fi # Set KUBE_MASTER detect-master # IMPORTANT: there are upstream things that rely on these files. # Do *not* fix this test by changing this path, unless you _really_ know # what you are doing. for file in kubecfg.key kubecfg.crt ca.crt; do echo "Checking for ${file}" "${GCLOUD}" compute ssh --zone="${ZONE}" "${KUBE_MASTER}" --command "ls /srv/kubernetes/${file}" done </del>
# The business logic for whether a given object should be created # was already enforced by salt, and /etc/kubernetes/addons is the # managed result is of that. Start everything below that directory. <del> echo "== Kubernetes addon manager started at $(date -Is) ==" </del> KUBECTL=/usr/local/bin/kubectl <ins> function create-object() { obj=$1 for tries in {1..5}; do if ${KUBECTL} --server="127.0.0.1:8080" create --validate=true -f ${obj}; then return fi echo "++ ${obj} failed, attempt ${try} (sleeping 5) ++" sleep 5 done } echo "== Kubernetes addon manager started at $(date -Is) ==" </ins> for obj in $(find /etc/kubernetes/addons -name *.yaml); do <del> ${KUBECTL} --server="127.0.0.1:8080" create -f ${obj} & </del> <ins> create-object ${obj} & </ins> echo "++ addon ${obj} started in pid $! ++" done noerrors="true"
detect-project &> /dev/null export PATH=$(get_absolute_dirname $kubectl):$PATH kubectl="${GCLOUD}" <del> fi if [[ "$KUBERNETES_PROVIDER" == "vagrant" ]]; then # When we are using vagrant it has hard coded auth.  We repeat that here so that # we don't clobber auth that might be used for a publicly facing cluster. config=( "--auth-path=$HOME/.kubernetes_vagrant_auth" ) elif [[ "${KUBERNETES_PROVIDER}" == "gke" ]]; then </del> # GKE runs kubectl through gcloud. config=( "preview"
"--zone=${ZONE}" "--cluster=${CLUSTER_NAME}" ) <ins> elif [[ "$KUBERNETES_PROVIDER" == "vagrant" ]]; then # When we are using vagrant it has hard coded auth.  We repeat that here so that # we don't clobber auth that might be used for a publicly facing cluster. config=( "--auth-path=$HOME/.kubernetes_vagrant_auth" ) </ins> fi <del> detect-master > /dev/null if [[ -n "${KUBE_MASTER_IP-}" && -z "${KUBERNETES_MASTER-}" ]]; then export KUBERNETES_MASTER=https://${KUBE_MASTER_IP} fi </del> <ins> echo "current-context: "$(${kubectl} config view -o template --template='{{index . "current-context"}}')"" </ins> echo "Running:" "${kubectl}" "${config[@]:+${config[@]}}" "${@+$@}" >&2 "${kubectl}" "${config[@]:+${config[@]}}" "${@+$@}"
<del> #!/bin/bash # Copyright 2014 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. function detect-master () { echo "Running locally" } </del>
This will build and start a lightweight local cluster, consisting of a master and a single minion. Type Control-C to shut it down. <del> You can use the cluster/kubectl.sh script to interact with the local cluster. You must set the KUBERNETES_PROVIDER environment variable. </del> <ins> You can use the cluster/kubectl.sh script to interact with the local cluster. hack/local-up-cluster.sh will print the commands to run to point kubectl at the local cluster. </ins> <del> ``` export KUBERNETES_PROVIDER=local ``` </del> ### Running a container
To start using your cluster, open up another terminal/tab and run: <del> export KUBERNETES_PROVIDER=local </del> <ins> cluster/kubectl.sh config set-cluster local --server=http://${API_HOST}:${API_PORT} --insecure-skip-tls-verify=true --global cluster/kubectl.sh config set-context local --cluster=local --global cluster/kubectl.sh config use-context local </ins> cluster/kubectl.sh EOF
//   3.  CurrentDirectoryPath //   4.  HomeDirectoryPath // Empty filenames are ignored.  Files with non-deserializable content produced errors. <del> // The first file to set a particular value or map key wins and the value or map key is never changed. // This means that the first file to set CurrentContext will have its context preserved.  It also means // that if two files specify a "red-user", only values from the first file's red-user are used.  Even </del> <ins> // The first file to set a particular map key wins and map key's value is never changed. // BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed. // This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two. // It also means that if two files specify a "red-user", only values from the first file's red-user are used.  Even </ins> // non-conflicting entries from the second file's "red-user" are discarded. // Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder // and only absolute file paths are returned. func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) { <del> config := clientcmdapi.NewConfig() mergeConfigWithFile(config, rules.CommandLinePath) resolveLocalPaths(rules.CommandLinePath, config) </del> <ins> kubeConfigFiles := []string{rules.CommandLinePath, rules.EnvVarPath, rules.CurrentDirectoryPath, rules.HomeDirectoryPath} </ins> <del> mergeConfigWithFile(config, rules.EnvVarPath) resolveLocalPaths(rules.EnvVarPath, config) </del> <ins> // first merge all of our maps mapConfig := clientcmdapi.NewConfig() for _, file := range kubeConfigFiles { mergeConfigWithFile(mapConfig, file) resolveLocalPaths(file, mapConfig) } </ins> <del> mergeConfigWithFile(config, rules.CurrentDirectoryPath) resolveLocalPaths(rules.CurrentDirectoryPath, config) </del> <ins> // merge all of the struct values in the reverse order so that priority is given correctly nonMapConfig := clientcmdapi.NewConfig() for i := len(kubeConfigFiles) - 1; i >= 0; i-- { file := kubeConfigFiles[i] mergeConfigWithFile(nonMapConfig, file) resolveLocalPaths(file, nonMapConfig) } </ins> <del> mergeConfigWithFile(config, rules.HomeDirectoryPath) resolveLocalPaths(rules.HomeDirectoryPath, config) </del> <ins> // since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and // get the values we expect. config := clientcmdapi.NewConfig() mergo.Merge(config, mapConfig) mergo.Merge(config, nonMapConfig) </ins> return config, nil }
} ) <ins> func TestConflictingCurrentContext(t *testing.T) { commandLineFile, _ := ioutil.TempFile("", "") defer os.Remove(commandLineFile.Name()) envVarFile, _ := ioutil.TempFile("", "") defer os.Remove(envVarFile.Name()) mockCommandLineConfig := clientcmdapi.Config{ CurrentContext: "any-context-value", } mockEnvVarConfig := clientcmdapi.Config{ CurrentContext: "a-different-context", } WriteToFile(mockCommandLineConfig, commandLineFile.Name()) WriteToFile(mockEnvVarConfig, envVarFile.Name()) loadingRules := ClientConfigLoadingRules{ CommandLinePath: commandLineFile.Name(), EnvVarPath:      envVarFile.Name(), } mergedConfig, err := loadingRules.Load() if err != nil { t.Errorf("Unexpected error: %v", err) } if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext { t.Errorf("expected %v, got %v", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext) } } </ins> func TestResolveRelativePaths(t *testing.T) { pathResolutionConfig1 := clientcmdapi.Config{ AuthInfos: map[string]clientcmdapi.AuthInfo{
} // TODO use generalized labels once they are implemented (#341) <del> b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand(cmd)). </del> <ins> b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()). </ins> NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam("kubernetes.io/cluster-service=true"). ResourceTypeOrNameArgs(false, []string{"services"}...).
return printer, nil } <del> // ClientMapperForCommand returns a ClientMapper for the given command and factory. func (f *Factory) ClientMapperForCommand(cmd *cobra.Command) resource.ClientMapper { </del> <ins> // ClientMapperForCommand returns a ClientMapper for the factory. func (f *Factory) ClientMapperForCommand() resource.ClientMapper { </ins> return resource.ClientMapperFunc(func(mapping *meta.RESTMapping) (resource.RESTClient, error) { return f.RESTClient(mapping) })
// handle watch separately since we cannot watch multiple resource types isWatch, isWatchOnly := util.GetFlagBool(cmd, "watch"), util.GetFlagBool(cmd, "watch-only") if isWatch || isWatchOnly { <del> r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). </del> <ins> r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). </ins> NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...).
mapper, typer := f.Object() // TODO: use resource.Builder instead <del> obj, err := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). </del> <ins> obj, err := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). </ins> NamespaceParam(cmdNamespace).RequireNamespace(). FilenameParam(filename). Do().
cmdNamespace, err := f.DefaultNamespace() cmdutil.CheckErr(err) mapper, typer := f.Object() <del> r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). </del> <ins> r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). </ins> ContinueOnError(). NamespaceParam(cmdNamespace).RequireNamespace(). ResourceTypeOrNameArgs(false, args...).
return func() (bool, error) { for i := range pods.Items { host, id, namespace := pods.Items[i].Status.Host, pods.Items[i].Name, pods.Items[i].Namespace <ins> glog.Infof("Check whether pod %s.%s exists on node %q", id, namespace, host) </ins> if len(host) == 0 { <ins> glog.Infof("Pod %s.%s is not bound to a host yet", id, namespace) </ins> return false, nil } if _, err := podInfo.GetPodStatus(host, namespace, id); err != nil {
// ResourceList is a set of (resource name, quantity) pairs. type ResourceList map[ResourceName]resource.Quantity <del> // Get is a convenience function, which returns a 0 quantity if the // resource list is nil, empty, or lacks a value for the requested resource. // Treat as read only! func (rl ResourceList) Get(name ResourceName) *resource.Quantity { if rl == nil { return &resource.Quantity{} } q := rl[name] return &q } </del> // Node is a worker node in Kubernetenes // The name of the node according to etcd is in ObjectMeta.Name. type Node struct {
HostPort int `json:"hostPort,omitempty"` // Required: This must be a valid port number, 0 < x < 65536. ContainerPort int `json:"containerPort"` <del> // Optional: Supports "TCP" and "UDP".  Defaults to "TCP". </del> <ins> // Required: Supports "TCP" and "UDP". </ins> Protocol Protocol `json:"protocol,omitempty"` // Optional: What host IP to bind the external port to. HostIP string `json:"hostIP,omitempty"`
LivenessProbe  *Probe               `json:"livenessProbe,omitempty"` ReadinessProbe *Probe               `json:"readinessProbe,omitempty"` Lifecycle      *Lifecycle           `json:"lifecycle,omitempty"` <del> // Optional: Defaults to /dev/termination-log </del> <ins> // Required. </ins> TerminationMessagePath string `json:"terminationMessagePath,omitempty"` // Optional: Default to false. Privileged bool `json:"privileged,omitempty"` <del> // Optional: Policy for pulling images for this container </del> <ins> // Required: Policy for pulling images for this container </ins> ImagePullPolicy PullPolicy `json:"imagePullPolicy"` // Optional: Capabilities for container. Capabilities Capabilities `json:"capabilities,omitempty"`
Volumes       []Volume      `json:"volumes"` Containers    []Container   `json:"containers"` RestartPolicy RestartPolicy `json:"restartPolicy,omitempty"` <del> // Optional: Set DNS policy.  Defaults to "ClusterFirst" </del> <ins> // Required: Set DNS policy. </ins> DNSPolicy DNSPolicy `json:"dnsPolicy,omitempty"` // NodeSelector is a selector which must be true for the pod to fit on a node NodeSelector map[string]string `json:"nodeSelector,omitempty"`
// Optional: If unspecified, the first port on the container will be used. ContainerPort util.IntOrString `json:"containerPort,omitempty"` <del> // Optional: Supports "ClientIP" and "None".  Used to maintain session affinity. </del> <ins> // Required: Supports "ClientIP" and "None".  Used to maintain session affinity. </ins> SessionAffinity AffinityType `json:"sessionAffinity,omitempty"` }
next_node=$(increment_ipv4 $next_node $node_subnet_count) done <del> CLUSTER_IP_RANGE="10.244.0.0/16" </del> <ins> CLUSTER_IP_RANGE="${KUBE_GCE_CLUSTER_CLASS_B:-10.244}.0.0/16" </ins> MINION_IP_RANGES=($(eval echo "${subnets[@]}")) MINION_SCOPES=("storage-ro" "compute-rw" "https://www.googleapis.com/auth/monitoring")
MASTER_NAME="${INSTANCE_PREFIX}-master" MASTER_TAG="${INSTANCE_PREFIX}-master" MINION_TAG="${INSTANCE_PREFIX}-minion" <del> CLUSTER_IP_RANGE="10.245.0.0/16" MINION_IP_RANGES=($(eval echo "10.245.{1..${NUM_MINIONS}}.0/24")) </del> <ins> CLUSTER_IP_RANGE="${KUBE_GCE_CLUSTER_CLASS_B:-10.245}.0.0/16" MINION_IP_RANGES=($(eval echo "${KUBE_GCE_CLUSTER_CLASS_B:-10.245}.{1..${NUM_MINIONS}}.0/24")) </ins> MASTER_IP_RANGE="${MASTER_IP_RANGE:-10.246.0.0/24}" MINION_SCOPES=("storage-ro" "compute-rw") # Increase the sleep interval value if concerned about API rate limits. 3, in seconds, is the default. POLL_SLEEP_INTERVAL=3
<ins> #!/bin/bash # 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. set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname "${BASH_SOURCE}")/.. function down-clusters { for count in $(seq 1 ${clusters}); do export KUBE_GCE_INSTANCE_PREFIX=e2e-test-${USER}-${count} local cluster_dir=${KUBE_ROOT}/_output/e2e/${KUBE_GCE_INSTANCE_PREFIX} export KUBECONFIG=${cluster_dir}/.kubeconfig go run ${KUBE_ROOT}/hack/e2e.go -down -v & done wait } function up-clusters { for count in $(seq 1 ${clusters}); do export KUBE_GCE_INSTANCE_PREFIX=e2e-test-${USER}-${count} export KUBE_GCE_CLUSTER_CLASS_B="10.$((${count}*2-1))" export MASTER_IP_RANGE="10.$((${count}*2)).0.0/24" local cluster_dir=${KUBE_ROOT}/_output/e2e/${KUBE_GCE_INSTANCE_PREFIX} mkdir -p ${cluster_dir} export KUBECONFIG=${cluster_dir}/.kubeconfig go run hack/e2e.go -up -v |& tee ${cluster_dir}/up.log & done fail=0 for job in $(jobs -p); do wait "${job}" || fail=$((fail + 1)) done if (( fail != 0 )); then echo "${fail} cluster creation failures. Not continuing with tests." exit 1 fi } function run-tests { for count in $(seq 1 ${clusters}); do export KUBE_GCE_INSTANCE_PREFIX=e2e-test-${USER}-${count} local cluster_dir=${KUBE_ROOT}/_output/e2e/${KUBE_GCE_INSTANCE_PREFIX} export KUBECONFIG=${cluster_dir}/.kubeconfig export E2E_REPORT_DIR=${cluster_dir} go run hack/e2e.go -test --test_args="--ginkgo.noColor" "${@:-}" -down |& tee ${cluster_dir}/e2e.log & done wait } # Outputs something like: # _output/e2e/e2e-test-zml-5/junit.xml #   FAIL: Shell tests that services.sh passes function post-process { echo $1 cat $1 | python -c ' import sys from xml.dom.minidom import parse failed = False for testcase in parse(sys.stdin).getElementsByTagName("testcase"): if len(testcase.getElementsByTagName("failure")) != 0: failed = True print "  FAIL: {test}".format(test = testcase.getAttribute("name")) if not failed: print "  SUCCESS!" ' } function print-results { for count in $(seq 1 ${clusters}); do for junit in ${KUBE_ROOT}/_output/e2e/e2e-test-${USER}-${count}/junit*.xml; do post-process ${junit} done done } if [[ ${KUBERNETES_PROVIDER:-gce} != "gce" ]]; then echo "$0 not supported on ${KUBERNETES_PROVIDER} yet" >&2 exit 1 fi readonly clusters=${1:-} if ! [[ "${clusters}" =~ ^[0-9]+$ ]]; then echo "Usage: ${0} <number of clusters> [options to hack/e2e.go]" >&2 exit 1 fi shift 1 rm -rf _output/e2e down-clusters up-clusters run-tests "${@:-}" print-results </ins>
{% if grains.network_mode is defined and grains.network_mode == 'openvswitch' %} <del> openvswitch: pkg: - installed service.running: - enable: True </del> sdn: cmd.wait: - name: /kubernetes-vagrant/network_closure.sh - watch: <del> - pkg: docker-io - pkg: openvswitch </del> <ins> - sls: docker </ins> {% endif %}
mkdir -p /etc/salt/minion.d cat <<EOF >/etc/salt/minion.d/master.conf master: '$(echo "$MASTER_NAME" | sed -e "s/'/''/g")' <ins> master: '$(echo "$MASTER_NAME" | sed -e "s/'/''/g")' auth_timeout: 10 auth_tries: 2 auth_safemode: True ping_interval: 1 random_reauth_delay: 3 state_aggregrate: - pkg </ins> EOF cat <<EOF >/etc/salt/minion.d/grains.conf
done # Let the minion know who its master is <ins> # Recover the salt-minion if the salt-master network changes ## auth_timeout - how long we want to wait for a time out ## auth_tries - how many times we will retry before restarting salt-minion ## auth_safemode - if our cert is rejected, we will restart salt minion ## ping_interval - restart the minion if we cannot ping the master after 1 minute ## random_reauth_delay - wait 0-3 seconds when reauthenticating ## recon_default - how long to wait before reconnecting ## recon_max - how long you will wait upper bound ## state_aggregrate - try to do a single yum command to install all referenced packages where possible at once, should improve startup times ## </ins> mkdir -p /etc/salt/minion.d cat <<EOF >/etc/salt/minion.d/master.conf master: '$(echo "$MASTER_NAME" | sed -e "s/'/''/g")' <ins> auth_timeout: 10 auth_tries: 2 auth_safemode: True ping_interval: 1 random_reauth_delay: 3 state_aggregrate: - pkg </ins> EOF cat <<EOF >/etc/salt/minion.d/log-level-debug.conf
return } <ins> // Redirect requests of the form "/{resource}/{name}" to "/{resource}/{name}/" // This is essentially a hack for https://github.com/GoogleCloudPlatform/kubernetes/issues/4958. // Note: Keep this code after tryUpgrade to not break that flow. if len(parts) == 2 && !strings.HasSuffix(req.URL.Path, "/") { w.Header().Set("Location", req.URL.Path+"/") w.WriteHeader(http.StatusMovedPermanently) return } </ins> proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: location.Scheme, Host: location.Host}) if transport == nil { prepend := path.Join(r.prefix, resource, id)
t.Fatalf("expected '%#v', got '%#v'", e, a) } } <ins> func TestRedirectOnMissingTrailingSlash(t *testing.T) { table := []struct { // The requested path path string // The path requested on the proxy server. proxyServerPath string }{ {"/trailing/slash/", "/trailing/slash/"}, {"/", "/"}, // "/" should be added at the end. {"", "/"}, // "/" should not be added at a non-root path. {"/some/path", "/some/path"}, } for _, item := range table { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != item.proxyServerPath { t.Errorf("Unexpected request on path: %s, expected path: %s, item: %v", req.URL.Path, item.proxyServerPath, item) } })) defer proxyServer.Close() serverURL, _ := url.Parse(proxyServer.URL) simpleStorage := &SimpleRESTStorage{ errors:                    map[string]error{}, resourceLocation:          serverURL, expectedResourceNamespace: "ns", } handler := handleNamespaced(map[string]rest.Storage{"foo": simpleStorage}) server := httptest.NewServer(handler) defer server.Close() proxyTestPattern := "/api/version/proxy/namespaces/ns/foo/id" + item.path req, err := http.NewRequest( "GET", server.URL+proxyTestPattern, strings.NewReader(""), ) if err != nil { t.Errorf("unexpected error %v", err) continue } // Note: We are using a default client here, that follows redirects. resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("unexpected error %v", err) continue } if resp.StatusCode != 200 { t.Errorf("Unexpected errorCode: %v, expected: 200. Response: %v, item: %v", resp.StatusCode, resp, item) } } } </ins>
t.Fatalf("expected '%#v', got '%#v'", e, a) } } <ins> func TestRedirectOnMissingTrailingSlash(t *testing.T) { table := []struct { // The requested path path string // The path requested on the proxy server. proxyServerPath string }{ {"/trailing/slash/", "/trailing/slash/"}, {"/", "/"}, // "/" should be added at the end. {"", "/"}, // "/" should not be added at a non-root path. {"/some/path", "/some/path"}, } for _, item := range table { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != item.proxyServerPath { t.Errorf("Unexpected request on path: %s, expected path: %s, item: %v", req.URL.Path, item.proxyServerPath, item) } })) defer proxyServer.Close() serverURL, _ := url.Parse(proxyServer.URL) simpleStorage := &SimpleRESTStorage{ errors:                    map[string]error{}, resourceLocation:          serverURL, expectedResourceNamespace: "ns", } handler := handleNamespaced(map[string]rest.Storage{"foo": simpleStorage}) server := httptest.NewServer(handler) defer server.Close() proxyTestPattern := "/api/version2/proxy/namespaces/ns/foo/id" + item.path req, err := http.NewRequest( "GET", server.URL+proxyTestPattern, strings.NewReader(""), ) if err != nil { t.Errorf("unexpected error %v", err) continue } // Note: We are using a default client here, that follows redirects. resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf("unexpected error %v", err) continue } if resp.StatusCode != http.StatusOK { t.Errorf("Unexpected errorCode: %v, expected: 200. Response: %v, item: %v", resp.StatusCode, resp, item) } } } </ins>
<del> #!/usr/bin/python # 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. import os import sys import yaml def mutate_env(path, var, value): # Load the existing arguments if os.path.exists(path): args = yaml.load(open(path)) else: args = {} args[var] = value yaml.dump(args, stream=open(path, 'w'), default_flow_style=False) if __name__ == "__main__": mutate_env(sys.argv[1], sys.argv[2], sys.argv[3]) </del>