func TestUnprivilegedNewProjectDenied(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } role, err := clusterAdminClient.ClusterRoles().Get(bootstrappolicy.SelfProvisionerRoleName) if err != nil { t.Fatalf("unexpected error: %v", err) } role.Rules = []authorizationapi.PolicyRule{} if _, err := clusterAdminClient.ClusterRoles().Update(role); err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig := *clusterAdminClientConfig valerieClientConfig.Username = "" valerieClientConfig.Password = "" valerieClientConfig.BearerToken = "" valerieClientConfig.CertFile = "" valerieClientConfig.KeyFile = "" valerieClientConfig.CertData = nil valerieClientConfig.KeyData = nil accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!") if err != nil { t.Fatalf("unexpected error: %v", err) } valerieClientConfig.BearerToken = accessToken valerieOpenshiftClient, err := client.New(&valerieClientConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } if err := testutil.WaitForClusterPolicyUpdate(valerieOpenshiftClient, "create", projectapi.Resource("projectrequests"), false); err != nil { t.Fatalf("unexpected error: %v", err) } // confirm that we have access to request the project _, err = valerieOpenshiftClient.ProjectRequests().List(kapi.ListOptions{}) if err == nil { t.Fatalf("expected error: %v", err) } expectedError := `You may not request a new project via this API.` if (err != nil) && (err.Error() != expectedError) { t.Fatalf("expected\n\t%v\ngot\n\t%v", expectedError, err.Error()) } }
func TestImageStreamDelete(t *testing.T) { _, clusterAdminKubeConfig, err := testutil.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } stream := mockImageStream() if err := clusterAdminClient.ImageStreams(testutil.Namespace()).Delete(stream.Name); err == nil || !errors.IsNotFound(err) { t.Fatalf("Unxpected non-error or type: %v", err) } actual, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(stream) if err != nil { t.Fatalf("Unexpected error: %v", err) } if err := clusterAdminClient.ImageStreams(testutil.Namespace()).Delete(actual.Name); err != nil { t.Fatalf("Unxpected error: %v", err) } }
func TestGroupCommands(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } newGroup := &groupscmd.NewGroupOptions{ GroupClient: clusterAdminClient.Groups(), Group: "group1", Users: []string{"first", "second", "third", "first"}, Printer: func(runtime.Object, io.Writer) error { return nil }, } if err := newGroup.AddGroup(); err != nil { t.Fatalf("unexpected error: %v", err) } group1, err := clusterAdminClient.Groups().Get("group1") if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := []string{"first", "second", "third"}, group1.Users; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, actual %v", e, a) } modifyUsers := &groupscmd.GroupModificationOptions{ GroupClient: clusterAdminClient.Groups(), Group: "group1", Users: []string{"second", "fourth", "fifth"}, } if err := modifyUsers.AddUsers(); err != nil { t.Fatalf("unexpected error: %v", err) } group1, err = clusterAdminClient.Groups().Get("group1") if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := []string{"first", "second", "third", "fourth", "fifth"}, group1.Users; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, actual %v", e, a) } if err := modifyUsers.RemoveUsers(); err != nil { t.Fatalf("unexpected error: %v", err) } group1, err = clusterAdminClient.Groups().Get("group1") if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := []string{"first", "third"}, group1.Users; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, actual %v", e, a) } }
func StartConfiguredMasterWithOptions(masterConfig *configapi.MasterConfig, testOptions TestOptions) (string, error) { if testOptions.DeleteAllEtcdKeys { util.DeleteAllEtcdKeys() } if err := start.NewMaster(masterConfig, true, true).Start(); err != nil { return "", err } adminKubeConfigFile := util.KubeConfigPath() clientConfig, err := util.GetClusterAdminClientConfig(adminKubeConfigFile) if err != nil { return "", err } masterURL, err := url.Parse(clientConfig.Host) if err != nil { return "", err } // wait for the server to come up: 35 seconds if err := cmdutil.WaitForSuccessfulDial(true, "tcp", masterURL.Host, 100*time.Millisecond, 1*time.Second, 35); err != nil { return "", err } for { // confirm that we can actually query from the api server if client, err := util.GetClusterAdminClient(adminKubeConfigFile); err == nil { if _, err := client.ClusterPolicies().List(labels.Everything(), fields.Everything()); err == nil { break } } time.Sleep(100 * time.Millisecond) } return adminKubeConfigFile, nil }
// RequireServer verifies if the etcd, docker and the OpenShift server are // available and you can successfully connected to them. func RequireServer() { util.RequireEtcd() util.RequireDocker() if _, err := util.GetClusterAdminClient(util.KubeConfigPath()); err != nil { os.Exit(1) } }
func setupImageStreamAdmissionTest(t *testing.T) (*kclient.Client, *client.Client) { testutil.RequireEtcd(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } kClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } _, err = client.ImageStreams(testutil.Namespace()).Create(&imageapi.ImageStream{ ObjectMeta: kapi.ObjectMeta{ Name: "src", }, }) if err != nil { t.Fatal(err) } return kClient, client }
func TestSimpleImageChangeBuildTriggerFromImageStreamTagCustomWithConfigChange(t *testing.T) { defer testutil.DumpEtcdOnFailure(t) projectAdminClient, _ := setup(t) clusterAdminClient, err := testutil.GetClusterAdminClient(testutil.GetBaseDir() + "/openshift.local.config/master/admin.kubeconfig") if err != nil { t.Fatalf("unexpected error: %v", err) } clusterRoleBindingAccessor := policy.NewClusterRoleBindingAccessor(clusterAdminClient) subjects := []kapi.ObjectReference{ { Kind: authorizationapi.SystemGroupKind, Name: bootstrappolicy.AuthenticatedGroup, }, } options := policy.RoleModificationOptions{ RoleNamespace: testutil.Namespace(), RoleName: bootstrappolicy.BuildStrategyCustomRoleName, RoleBindingAccessor: clusterRoleBindingAccessor, Subjects: subjects, } options.AddRole() if err := testutil.WaitForPolicyUpdate(projectAdminClient, testutil.Namespace(), "create", buildapi.Resource(authorizationapi.CustomBuildResource), true); err != nil { t.Fatal(err) } imageStream := mockImageStream2(tag) imageStreamMapping := mockImageStreamMapping(imageStream.Name, "someimage", tag, "registry:8080/openshift/test-image-trigger:"+tag) strategy := customStrategy("ImageStreamTag", streamName+":"+tag) config := imageChangeBuildConfigWithConfigChange("custom-imagestreamtag", strategy) runTest(t, "SimpleImageChangeBuildTriggerFromImageStreamTagCustom", projectAdminClient, imageStream, imageStreamMapping, config, tag) }
func setupImageStreamAdmissionTest(t *testing.T) (*kclient.Client, *client.Client) { testutil.RequireEtcd(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } kClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } for { _, err = client.ImageStreams(testutil.Namespace()).Create(newImageStreamWithSpecTags("src", nil)) t.Logf("initing: %v", err) if err != nil { if errForbiddenWithRetry(err) { t.Logf("waiting for limit ranger to catch up: %v", err) continue } t.Fatalf("err: %#v", err) } break } return kClient, client }
func setupProjectRequestLimitTest(t *testing.T, pluginConfig *requestlimit.ProjectRequestLimitConfig) (kclient.Interface, client.Interface, *kclient.Config) { masterConfig, err := testserver.DefaultMasterOptions() if err != nil { t.Fatalf("error creating config: %v", err) } masterConfig.AdmissionConfig.PluginOrderOverride = []string{"OriginNamespaceLifecycle", "BuildByStrategy", "ProjectRequestLimit"} masterConfig.AdmissionConfig.PluginConfig = map[string]configapi.AdmissionPluginConfig{ "ProjectRequestLimit": { Configuration: runtime.EmbeddedObject{ Object: pluginConfig, }, }, } kubeConfigFile, err := testserver.StartConfiguredMaster(masterConfig) if err != nil { t.Fatalf("error starting server: %v", err) } kubeClient, err := testutil.GetClusterAdminKubeClient(kubeConfigFile) if err != nil { t.Fatalf("error getting client: %v", err) } openshiftClient, err := testutil.GetClusterAdminClient(kubeConfigFile) if err != nil { t.Fatalf("error getting openshift client: %v", err) } clientConfig, err := testutil.GetClusterAdminClientConfig(kubeConfigFile) if err != nil { t.Fatalf("error getting client config: %v", err) } return kubeClient, openshiftClient, clientConfig }
// TestProjectMustExist verifies that content cannot be added in a project that does not exist func TestProjectMustExist(t *testing.T) { testutil.RequireEtcd(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminKubeClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } pod := &kapi.Pod{ ObjectMeta: kapi.ObjectMeta{Name: "pod"}, Spec: kapi.PodSpec{ Containers: []kapi.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}}, RestartPolicy: kapi.RestartPolicyAlways, DNSPolicy: kapi.DNSClusterFirst, }, } _, err = clusterAdminKubeClient.Pods("test").Create(pod) if err == nil { t.Errorf("Expected an error on creation of a Kubernetes resource because namespace does not exist") } build := &buildapi.Build{ ObjectMeta: kapi.ObjectMeta{Name: "buildid", Namespace: "default"}, Spec: buildapi.BuildSpec{ Source: buildapi.BuildSource{ Git: &buildapi.GitBuildSource{ URI: "http://github.com/my/repository", }, ContextDir: "context", }, Strategy: buildapi.BuildStrategy{ DockerStrategy: &buildapi.DockerBuildStrategy{}, }, Output: buildapi.BuildOutput{ To: &kapi.ObjectReference{ Kind: "DockerImage", Name: "repository/data", }, }, }, Status: buildapi.BuildStatus{ Phase: buildapi.BuildPhaseNew, }, } _, err = clusterAdminClient.Builds("test").Create(build) if err == nil { t.Errorf("Expected an error on creation of a Origin resource because namespace does not exist") } }
func setupProjectRequestLimitTest(t *testing.T, pluginConfig *requestlimit.ProjectRequestLimitConfig) (kclientset.Interface, client.Interface, *restclient.Config) { testutil.RequireEtcd(t) masterConfig, err := testserver.DefaultMasterOptions() if err != nil { t.Fatalf("error creating config: %v", err) } masterConfig.AdmissionConfig.PluginConfig = map[string]configapi.AdmissionPluginConfig{ "ProjectRequestLimit": { Configuration: pluginConfig, }, } kubeConfigFile, err := testserver.StartConfiguredMaster(masterConfig) if err != nil { t.Fatalf("error starting server: %v", err) } kubeClient, err := testutil.GetClusterAdminKubeClient(kubeConfigFile) if err != nil { t.Fatalf("error getting client: %v", err) } openshiftClient, err := testutil.GetClusterAdminClient(kubeConfigFile) if err != nil { t.Fatalf("error getting openshift client: %v", err) } clientConfig, err := testutil.GetClusterAdminClientConfig(kubeConfigFile) if err != nil { t.Fatalf("error getting client config: %v", err) } return kubeClient, openshiftClient, clientConfig }
func setupClusterResourceOverrideTest(t *testing.T, pluginConfig *overrideapi.ClusterResourceOverrideConfig) kclient.Interface { masterConfig, err := testserver.DefaultMasterOptions() checkErr(t, err) // fill in possibly-empty config values if masterConfig.KubernetesMasterConfig == nil { masterConfig.KubernetesMasterConfig = &api.KubernetesMasterConfig{} } kubeMaster := masterConfig.KubernetesMasterConfig if kubeMaster.AdmissionConfig.PluginConfig == nil { kubeMaster.AdmissionConfig.PluginConfig = map[string]api.AdmissionPluginConfig{} } // set our config as desired kubeMaster.AdmissionConfig.PluginConfig[overrideapi.PluginName] = api.AdmissionPluginConfig{Configuration: pluginConfig} // start up a server and return useful clients to that server clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterConfig) checkErr(t, err) clusterAdminKubeClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) checkErr(t, err) clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) checkErr(t, err) // need to create a project and return client for project admin clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) checkErr(t, err) _, err = testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, testutil.Namespace(), "peon") checkErr(t, err) checkErr(t, testserver.WaitForServiceAccounts(clusterAdminKubeClient, testutil.Namespace(), []string{bootstrappolicy.DefaultServiceAccountName})) return clusterAdminKubeClient }
func TestImageStreamList(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } builds, err := clusterAdminClient.ImageStreams(testutil.Namespace()).List(kapi.ListOptions{}) if err != nil { t.Fatalf("Unexpected error %v", err) } if len(builds.Items) != 0 { t.Errorf("Expected no builds, got %#v", builds.Items) } }
// TestSTIEnvironmentBuild exercises the scenario where you have .sti/environment // file in your source code repository and you use STI build strategy. In that // case the STI build should read that file and set all environment variables // from that file to output image. func TestSTIEnvironmentBuild(t *testing.T) { namespace := testutil.RandomNamespace("stienv") fmt.Printf("Using '%s' namespace\n", namespace) build := testutil.GetBuildFixture("fixtures/test-env-build.json") client, _ := testutil.GetClusterAdminClient(testutil.KubeConfigPath()) stream := testutil.CreateSampleImageStream(namespace) if stream == nil { t.Fatal("Failed to create ImageStream") } defer testutil.DeleteSampleImageStream(stream, namespace) // TODO: Tweak the selector to match the build name watcher, err := client.Builds(namespace).Watch(labels.Everything(), fields.Everything(), "0") if err != nil { t.Fatalf("Failed to create watcher: %v", err) } defer watcher.Stop() newBuild, err := client.Builds(namespace).Create(build) if err != nil { t.Fatalf("Unexpected error: %v", err) } waitForComplete(newBuild, watcher, t) if err := testutil.VerifyImage(stream, "", namespace, validateSTIEnvironment); err != nil { t.Fatalf("The build image failed validation: %v", err) } }
func TestTemplateTransformationFromConfig(t *testing.T) { _, clusterAdminKubeConfig, err := testserver.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } walkJSONFiles("../templates/fixtures", func(name, path string, data []byte) { template, err := runtime.Decode(kapi.Codecs.UniversalDecoder(), data) if err != nil { t.Errorf("%q: unexpected error: %v", path, err) return } config, err := clusterAdminClient.TemplateConfigs("default").Create(template.(*templateapi.Template)) if err != nil { t.Errorf("%q: unexpected error: %v", path, err) return } if len(config.Objects) == 0 { t.Errorf("%q: no items in config object", path) return } t.Logf("tested %q", path) }) }
func setupBuildStrategyTest(t *testing.T) (clusterAdminClient, projectAdminClient, projectEditorClient *client.Client) { namespace := testutil.Namespace() _, clusterAdminKubeConfig, err := testserver.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err = testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } projectAdminClient, err = testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, namespace, "harold") if err != nil { t.Fatalf("unexpected error: %v", err) } projectEditorClient, _, _, err = testutil.GetClientForUser(*clusterAdminClientConfig, "joe") if err != nil { t.Fatalf("unexpected error: %v", err) } addJoe := &policy.RoleModificationOptions{ RoleNamespace: "", RoleName: bootstrappolicy.EditRoleName, RoleBindingAccessor: policy.NewLocalRoleBindingAccessor(namespace, projectAdminClient), Users: []string{"joe"}, } if err := addJoe.AddRole(); err != nil { t.Fatalf("unexpected error: %v", err) } if err := testutil.WaitForPolicyUpdate(projectEditorClient, namespace, "create", authorizationapi.DockerBuildResource, true); err != nil { t.Fatalf(err.Error()) } // Create builder image stream and tag imageStream := &imageapi.ImageStream{} imageStream.Name = "builderimage" _, err = clusterAdminClient.ImageStreams(testutil.Namespace()).Create(imageStream) if err != nil { t.Fatalf("Couldn't create ImageStream: %v", err) } // Create image stream mapping imageStreamMapping := &imageapi.ImageStreamMapping{} imageStreamMapping.Name = "builderimage" imageStreamMapping.Tag = "latest" imageStreamMapping.Image.Name = "image-id" imageStreamMapping.Image.DockerImageReference = "test/builderimage:latest" err = clusterAdminClient.ImageStreamMappings(testutil.Namespace()).Create(imageStreamMapping) if err != nil { t.Fatalf("Couldn't create ImageStreamMapping: %v", err) } return }
func makeNamespaceGlobal(ns *api.Namespace) { client, err := testutil.GetClusterAdminClient(testexutil.KubeConfigPath()) expectNoError(err) netns, err := client.NetNamespaces().Get(ns.Name) expectNoError(err) netns.NetID = 0 _, err = client.NetNamespaces().Update(netns) expectNoError(err) }
func TestWebhookGitHubPing(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMaster() if err != nil { t.Fatalf("unable to start master: %v", err) } kubeClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unable to get kubeClient: %v", err) } osClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unable to get osClient: %v", err) } kubeClient.Core().Namespaces().Create(&kapi.Namespace{ ObjectMeta: kapi.ObjectMeta{Name: testutil.Namespace()}, }) // create buildconfig buildConfig := mockBuildConfigImageParms("originalimage", "imagestream", "validtag") if _, err := osClient.BuildConfigs(testutil.Namespace()).Create(buildConfig); err != nil { t.Fatalf("Unexpected error: %v", err) } watch, err := osClient.Builds(testutil.Namespace()).Watch(kapi.ListOptions{}) if err != nil { t.Fatalf("Couldn't subscribe to builds: %v", err) } defer watch.Stop() for _, s := range []string{ "/oapi/v1/namespaces/" + testutil.Namespace() + "/buildconfigs/pushbuild/webhooks/secret101/github", "/oapi/v1/namespaces/" + testutil.Namespace() + "/buildconfigs/pushbuild/webhooks/secret100/github", "/oapi/v1/namespaces/" + testutil.Namespace() + "/buildconfigs/pushbuild/webhooks/secret102/github", } { // trigger build event sending push notification clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } postFile(osClient.RESTClient.Client, "ping", "pingevent.json", clusterAdminClientConfig.Host+s, http.StatusOK, t) // TODO: improve negative testing timer := time.NewTimer(time.Second / 2) select { case <-timer.C: // nothing should happen case event := <-watch.ResultChan(): build := event.Object.(*buildapi.Build) t.Fatalf("Unexpected build created: %#v", build) } } }
func TestDeployScale(t *testing.T) { const namespace = "test-deploy-scale" testutil.RequireEtcd(t) _, clusterAdminKubeConfig, err := testserver.StartTestMaster() checkErr(t, err) clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) checkErr(t, err) clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) checkErr(t, err) _, err = testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, namespace, "my-test-user") checkErr(t, err) osClient, _, _, err := testutil.GetClientForUser(*clusterAdminClientConfig, "my-test-user") checkErr(t, err) config := deploytest.OkDeploymentConfig(0) config.Spec.Triggers = []deployapi.DeploymentTriggerPolicy{} config.Spec.Replicas = 1 dc, err := osClient.DeploymentConfigs(namespace).Create(config) if err != nil { t.Fatalf("Couldn't create DeploymentConfig: %v %#v", err, config) } scale, err := osClient.DeploymentConfigs(namespace).GetScale(config.Name) if err != nil { t.Fatalf("Couldn't get DeploymentConfig scale: %v", err) } if scale.Spec.Replicas != 1 { t.Fatalf("Expected scale.spec.replicas=1, got %#v", scale) } scaleUpdate := &extensions.Scale{ ObjectMeta: kapi.ObjectMeta{ Name: dc.Name, Namespace: namespace, }, Spec: extensions.ScaleSpec{Replicas: 3}, } updatedScale, err := osClient.DeploymentConfigs(namespace).UpdateScale(scaleUpdate) if err != nil { // If this complains about "Scale" not being registered in "v1", check the kind overrides in the API registration in SubresourceGroupVersionKind t.Fatalf("Couldn't update DeploymentConfig scale to %#v: %v", scaleUpdate, err) } if updatedScale.Spec.Replicas != 3 { t.Fatalf("Expected scale.spec.replicas=3, got %#v", scale) } persistedScale, err := osClient.DeploymentConfigs(namespace).GetScale(config.Name) if err != nil { t.Fatalf("Couldn't get DeploymentConfig scale: %v", err) } if persistedScale.Spec.Replicas != 3 { t.Fatalf("Expected scale.spec.replicas=3, got %#v", scale) } }
func TestAuthorizationRestrictedAccessForProjectAdmins(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } haroldClient, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, "hammer-project", "harold") if err != nil { t.Fatalf("unexpected error: %v", err) } markClient, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, "mallet-project", "mark") if err != nil { t.Fatalf("unexpected error: %v", err) } _, err = haroldClient.DeploymentConfigs("hammer-project").List(kapi.ListOptions{}) if err != nil { t.Fatalf("unexpected error: %v", err) } _, err = markClient.DeploymentConfigs("hammer-project").List(kapi.ListOptions{}) if (err == nil) || !kapierror.IsForbidden(err) { t.Fatalf("unexpected error: %v", err) } // projects are a special case where a get of a project actually sets a namespace. Make sure that // the namespace is properly special cased and set for authorization rules _, err = haroldClient.Projects().Get("hammer-project") if err != nil { t.Fatalf("unexpected error: %v", err) } _, err = markClient.Projects().Get("hammer-project") if (err == nil) || !kapierror.IsForbidden(err) { t.Fatalf("unexpected error: %v", err) } // wait for the project authorization cache to catch the change. It is on a one second period waitForProject(t, haroldClient, "hammer-project", 1*time.Second, 10) waitForProject(t, markClient, "mallet-project", 1*time.Second, 10) }
func setupUserPodNodeConstraintsTest(t *testing.T, pluginConfig *pluginapi.PodNodeConstraintsConfig, user string) (*client.Client, *kclientset.Clientset) { testutil.RequireEtcd(t) masterConfig, err := testserver.DefaultMasterOptions() if err != nil { t.Fatalf("error creating config: %v", err) } cfg := map[string]configapi.AdmissionPluginConfig{ "PodNodeConstraints": { Configuration: pluginConfig, }, } masterConfig.AdmissionConfig.PluginConfig = cfg masterConfig.KubernetesMasterConfig.AdmissionConfig.PluginConfig = cfg kubeConfigFile, err := testserver.StartConfiguredMaster(masterConfig) if err != nil { t.Fatalf("error starting server: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(kubeConfigFile) if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(kubeConfigFile) if err != nil { t.Fatalf("unexpected error: %v", err) } userClient, userkubeClientset, _, err := testutil.GetClientForUser(*clusterAdminClientConfig, user) if err != nil { t.Fatalf("error getting user/kube client: %v", err) } kubeClientset, err := testutil.GetClusterAdminKubeClient(kubeConfigFile) if err != nil { t.Fatalf("error getting kube client: %v", err) } ns := &kapi.Namespace{} ns.Name = testutil.Namespace() _, err = kubeClientset.Core().Namespaces().Create(ns) if err != nil { t.Fatalf("error creating namespace: %v", err) } if err := testserver.WaitForServiceAccounts(kubeClientset, testutil.Namespace(), []string{bootstrappolicy.DefaultServiceAccountName}); err != nil { t.Fatalf("unexpected error: %v", err) } addUser := &policy.RoleModificationOptions{ RoleNamespace: ns.Name, RoleName: bootstrappolicy.AdminRoleName, RoleBindingAccessor: policy.NewClusterRoleBindingAccessor(clusterAdminClient), Users: []string{user}, } if err := addUser.AddRole(); err != nil { t.Fatalf("unexpected error: %v", err) } return userClient, userkubeClientset }
func setupBuildControllerTest(counts controllerCount, t *testing.T) (*client.Client, *kclientset.Clientset) { testutil.RequireEtcd(t) master, clusterAdminKubeConfig, err := testserver.StartTestMaster() if err != nil { t.Fatal(err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatal(err) } clusterAdminKubeClientset, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) if err != nil { t.Fatal(err) } _, err = clusterAdminKubeClientset.Core().Namespaces().Create(&kapi.Namespace{ ObjectMeta: kapi.ObjectMeta{Name: testutil.Namespace()}, }) if err != nil { t.Fatal(err) } if err := testserver.WaitForServiceAccounts(clusterAdminKubeClientset, testutil.Namespace(), []string{bootstrappolicy.BuilderServiceAccountName, bootstrappolicy.DefaultServiceAccountName}); err != nil { t.Fatalf("unexpected error: %v", err) } openshiftConfig, err := origin.BuildMasterConfig(*master) if err != nil { t.Fatal(err) } // Get the build controller clients, since those rely on service account tokens // We don't want to proceed with the rest of the test until those are available openshiftConfig.BuildControllerClients() for i := 0; i < counts.BuildControllers; i++ { openshiftConfig.RunBuildController(openshiftConfig.Informers) } for i := 0; i < counts.BuildPodControllers; i++ { openshiftConfig.RunBuildPodController() } for i := 0; i < counts.ImageChangeControllers; i++ { openshiftConfig.RunBuildImageChangeTriggerController() } for i := 0; i < counts.ConfigChangeControllers; i++ { openshiftConfig.RunBuildConfigChangeController() } return clusterAdminClient, clusterAdminKubeClientset }
// TestPushSecretName exercises one of the complex Build scenarios, where you // first build a Docker image using Docker build strategy, which will later by // consumed by Custom build strategy to verify that the 'PushSecretName' (Docker // credentials) were successfully transported to the builder. The content of the // Secret file is verified in the end. func TestPushSecretName(t *testing.T) { namespace := testutil.RandomNamespace("secret") client, _ := testutil.GetClusterAdminClient(testutil.KubeConfigPath()) kclient, _ := testutil.GetClusterAdminKubeClient(testutil.KubeConfigPath()) stream := testutil.CreateSampleImageStream(namespace) if stream == nil { t.Fatal("Failed to create ImageStream") } defer testutil.DeleteSampleImageStream(stream, namespace) // Create Secret with dockercfg secret := testutil.GetSecretFixture("fixtures/test-secret.json") // TODO: Why do I need to set namespace here? secret.Namespace = namespace _, err := kclient.Secrets(namespace).Create(secret) if err != nil { t.Fatalf("Failed to create Secret: %v", err) } watcher, err := client.Builds(namespace).Watch(labels.Everything(), fields.Everything(), "0") if err != nil { t.Fatalf("Failed to create watcher: %v", err) } defer watcher.Stop() // First build the builder image (custom build builder) dockerBuild := testutil.GetBuildFixture("fixtures/test-secret-build.json") newDockerBuild, err := client.Builds(namespace).Create(dockerBuild) if err != nil { t.Fatalf("Unable to create Build %s: %v", dockerBuild.Name, err) } waitForComplete(newDockerBuild, watcher, t) // Now build the application image using custom build (run the previous image) // Custom build will copy the dockercfg file into the application image. customBuild := testutil.GetBuildFixture("fixtures/test-custom-build.json") imageName := fmt.Sprintf("%s/%s/%s", os.Getenv("REGISTRY_ADDR"), namespace, stream.Name) customBuild.Parameters.Strategy.CustomStrategy.Image = imageName newCustomBuild, err := client.Builds(namespace).Create(customBuild) if err != nil { t.Fatalf("Unable to create Build %s: %v", dockerBuild.Name, err) } waitForComplete(newCustomBuild, watcher, t) // Verify that the dockercfg file is there if err := testutil.VerifyImage(stream, "application", namespace, validatePushSecret); err != nil { t.Fatalf("Image verification failed: %v", err) } }
func TestBootstrapPolicyOverwritePolicyCommand(t *testing.T) { testutil.RequireEtcd(t) masterConfig, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } if err := client.ClusterPolicies().Delete(authorizationapi.PolicyName); err != nil { t.Errorf("unexpected error: %v", err) } // after the policy is deleted, we must wait for it to be cleared from the policy cache err = wait.Poll(10*time.Millisecond, 10*time.Second, func() (bool, error) { _, err := client.ClusterPolicies().List(kapi.ListOptions{}) if err == nil { return false, nil } if !kapierror.IsForbidden(err) { t.Errorf("unexpected error: %v", err) } return true, nil }) if err != nil { t.Errorf("timeout: %v", err) } etcdClient, err := etcd.MakeNewEtcdClient(masterConfig.EtcdClientInfo) if err != nil { t.Errorf("unexpected error: %v", err) } storageVersion := unversioned.GroupVersion{Group: "", Version: masterConfig.EtcdStorageConfig.OpenShiftStorageVersion} etcdHelper, err := origin.NewEtcdStorage(etcdClient, storageVersion, masterConfig.EtcdStorageConfig.OpenShiftStoragePrefix) if err != nil { t.Errorf("unexpected error: %v", err) } if err := admin.OverwriteBootstrapPolicy(etcdHelper, masterConfig.PolicyConfig.BootstrapPolicyFile, admin.CreateBootstrapPolicyFileFullCommand, true, ioutil.Discard); err != nil { t.Errorf("unexpected error: %v", err) } if _, err := client.ClusterPolicies().List(kapi.ListOptions{}); err != nil { t.Errorf("unexpected error: %v", err) } }
func TestGroupCommands(t *testing.T) { _, clusterAdminKubeConfig, err := testutil.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } newGroup := &groupscmd.NewGroupOptions{clusterAdminClient.Groups(), "group1", []string{"first", "second", "third", "first"}} if err := newGroup.AddGroup(); err != nil { t.Fatalf("unexpected error: %v", err) } group1, err := clusterAdminClient.Groups().Get("group1") if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := []string{"first", "second", "third"}, group1.Users; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, actual %v", e, a) } modifyUsers := &groupscmd.GroupModificationOptions{clusterAdminClient.Groups(), "group1", []string{"second", "fourth", "fifth"}} if err := modifyUsers.AddUsers(); err != nil { t.Fatalf("unexpected error: %v", err) } group1, err = clusterAdminClient.Groups().Get("group1") if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := []string{"first", "second", "third", "fourth", "fifth"}, group1.Users; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, actual %v", e, a) } if err := modifyUsers.RemoveUsers(); err != nil { t.Fatalf("unexpected error: %v", err) } group1, err = clusterAdminClient.Groups().Get("group1") if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := []string{"first", "third"}, group1.Users; !reflect.DeepEqual(e, a) { t.Errorf("expected %v, actual %v", e, a) } }
func TestImageStreamCreate(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } stream := mockImageStream() if _, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(&imageapi.ImageStream{}); err == nil || !errors.IsInvalid(err) { t.Fatalf("Unexpected error: %v", err) } expected, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(stream) if err != nil { t.Fatalf("Unexpected error: %v", err) } if expected.Name == "" { t.Errorf("Unexpected empty image Name %v", expected) } actual, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Get(stream.Name) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !reflect.DeepEqual(expected, actual) { t.Errorf("unexpected object: %s", diff.ObjectDiff(expected, actual)) } streams, err := clusterAdminClient.ImageStreams(testutil.Namespace()).List(kapi.ListOptions{}) if err != nil { t.Fatalf("Unexpected error %v", err) } if len(streams.Items) != 1 { t.Errorf("Expected one image, got %#v", streams.Items) } }
func TestImageStreamCreate(t *testing.T) { _, clusterAdminKubeConfig, err := testutil.StartTestMaster() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } stream := mockImageStream() if _, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(&imageapi.ImageStream{}); err == nil || !errors.IsInvalid(err) { t.Fatalf("Unexpected error: %v", err) } expected, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(stream) if err != nil { t.Fatalf("Unexpected error: %v", err) } if expected.Name == "" { t.Errorf("Unexpected empty image Name %v", expected) } actual, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Get(stream.Name) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !reflect.DeepEqual(expected, actual) { t.Errorf("unexpected object: %s", util.ObjectDiff(expected, actual)) } streams, err := clusterAdminClient.ImageStreams(testutil.Namespace()).List(labels.Everything(), fields.Everything()) if err != nil { t.Fatalf("Unexpected error %v", err) } if len(streams.Items) != 1 { t.Errorf("Expected one image, got %#v", streams.Items) } }
// launchAPI launches an api server and returns clients configured to // access it. func launchApi() (osclient.Interface, kclient.Interface, error) { _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { return nil, nil, err } kc, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig) if err != nil { return nil, nil, err } oc, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { return nil, nil, err } return oc, kc, nil }
func TestScopedImpersonation(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } projectName := "hammer-project" userName := "******" if _, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, projectName, userName); err != nil { t.Fatalf("unexpected error: %v", err) } err = clusterAdminClient.Get(). SetHeader(authenticationapi.ImpersonateUserHeader, "harold"). SetHeader(authenticationapi.ImpersonateUserScopeHeader, "user:info"). Namespace(projectName).Resource("builds").Name("name").Do().Into(&buildapi.Build{}) if !kapierrors.IsForbidden(err) { t.Fatalf("unexpected error: %v", err) } user := &userapi.User{} err = clusterAdminClient.Get(). SetHeader(authenticationapi.ImpersonateUserHeader, "harold"). SetHeader(authenticationapi.ImpersonateUserScopeHeader, "user:info"). Resource("users").Name("~").Do().Into(user) if err != nil { t.Fatalf("unexpected error: %v", err) } if user.Name != "harold" { t.Fatalf("expected %v, got %v", "harold", user.Name) } }
func TestBootstrapPolicyOverwritePolicyCommand(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) masterConfig, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } if err := client.ClusterPolicies().Delete(authorizationapi.PolicyName); err != nil { t.Errorf("unexpected error: %v", err) } // after the policy is deleted, we must wait for it to be cleared from the policy cache err = wait.Poll(10*time.Millisecond, 10*time.Second, func() (bool, error) { _, err := client.ClusterPolicies().List(kapi.ListOptions{}) if err == nil { return false, nil } if !kapierror.IsForbidden(err) { t.Errorf("unexpected error: %v", err) } return true, nil }) if err != nil { t.Errorf("timeout: %v", err) } optsGetter := restoptions.NewConfigGetter(*masterConfig) if err := admin.OverwriteBootstrapPolicy(optsGetter, masterConfig.PolicyConfig.BootstrapPolicyFile, admin.CreateBootstrapPolicyFileFullCommand, true, ioutil.Discard); err != nil { t.Errorf("unexpected error: %v", err) } if _, err := client.ClusterPolicies().List(kapi.ListOptions{}); err != nil { t.Errorf("unexpected error: %v", err) } }