Beispiel #1
0
    def configFileCreationTest(self, d, hostNameEntry, apiTokenEntry):
        """Test basic functionality. You call config and specify the
        entries. The generated config file should contain the same information"""

        args = ["config"]
        wc = wavectl.Wavectl(designForTestArgv=args, designForTestConfigDir=d)

        input = StringIO()
        input.write(hostNameEntry)
        input.write(apiTokenEntry)

        with util.StdinRedirect(input) as redIn:
            wc.runCmd()

        # In the config dir, a config file must be created.
        self.assertListEqual([wc.config.configFileName], os.listdir(d))

        fn = os.path.join(d, wc.config.configFileName)
        with open(fn) as f:
            c = json.load(f)

        # Check the values in the read config.
        self.assertDictEqual(
            c,
            {wc.config.wavefrontHostKey: hostNameEntry.strip(),
                wc.config.apiTokenKey: apiTokenEntry.strip(),
             })
Beispiel #2
0
    def executePush(self,
                    rsrcType,
                    target,
                    pushAdditionalParams=[],
                    rsrcAdditionalParams=[]):

        logging.info("Starting executePush")

        assert os.path.isdir(target) or os.path.isfile(target) \
            and "The target of the push should be a directory or a file"

        args = ["push", target,
                "--wavefrontHost", util.wavefrontHostName,
                "--apiToken", util.wavefrontApiToken] \
            + pushAdditionalParams \
            + [rsrcType] \
            + rsrcAdditionalParams

        wc = wavectl.Wavectl(designForTestArgv=args)

        with util.StdoutCapture() as captOut:
            wc.runCmd()

        logging.info("Completed executePush")
        return captOut.str()
Beispiel #3
0
    def repoWorkingTreeIsDirtyInUsedDir(self, cmd, rsrcType, rsrcs, error):
        """ Git repo has local modifications to tracked files that have not
        been staged yet in the same dir as the pull/push dir. The working tree is
        dirty. The command should not allow a pull or a push to execute in this
        state"""

        with TempDir() as td:
            d = td.dir()
            r = self.repoInit(d)

            self.addReadmeFileToRepo(r)
            n = "newFile"
            self.addNewFileToRepo(r, n)

            r.index.commit("Initial commit of {} file".format(n),skip_hooks=True)

            # After committing the following changes will be local modification that
            # are not staged yet.
            fn = os.path.join(d, n)

            with open(fn, "r+") as f:
                f.write("Some new modification")

            args = [cmd, d, "--inGit", rsrcType]
            wc = wavectl.Wavectl(
                designForTestArgv=args,
                designForTestRsrcs=rsrcs)

            self.assertRaisesRegexp(
                error,
                (r"The path at .+ is dirty. "
                 r"Please commit your outstanding changes .*"),
                wc.runCmd)
Beispiel #4
0
    def existingRepoDirNotGit(self, cmd, rsrcType, rsrcs):
        """ The repoDir is an existing directory however it is not a source
        controlled directory. The pull resource  command should raise an exception"""

        with TempDir() as td:
            d = td.dir()
            args = [cmd, d, "--inGit", rsrcType]
            wc = wavectl.Wavectl(designForTestArgv=args,
                                 designForTestRsrcs=rsrcs)
            self.assertRaises(git.exc.InvalidGitRepositoryError, wc.runCmd)
Beispiel #5
0
    def repoIsDirtyInDifferentDir(self, rsrcType, rsrcs, whatIsDirty):
        """Execute a pull operation on a git repo that is dirty because of
        some changes in another directory than the pull directory. Depending on
        the whatIsDirty parameter the changes may be staged or not-yet-staged."""
        with util.TempDir() as td:
            d = td.dir()
            r = self.repoInit(d)

            self.addReadmeFileToRepo(r)
            self.createPullBranch(r, wavectl.PullCommand.datetimeFormat,
                                  wavectl.PullCommand.pullBranchSuffix)

            cleanSubdirName = "cleanSubdir"
            cleanSubdir = os.path.join(d, cleanSubdirName)
            os.mkdir(cleanSubdir)

            dirtySubdirName = "dirtySubdir"
            dirtySubdir = os.path.join(d, dirtySubdirName)
            os.mkdir(dirtySubdir)

            newFileName = "file1"
            self.addNewFileToRepo(r, newFileName, subdir=dirtySubdirName)

            if whatIsDirty == self.index:
                pass
            elif whatIsDirty == self.workingTree:
                # In order to make the working tree dirty we commit the file
                # and make a local modification on it.
                r.index.commit(
                    "Initial commit of {0} file".format(newFileName),
                    skip_hooks=True)

                # File1 has local modifications in a separate subdir from the
                # actual pull directory.
                fp = os.path.join(d, dirtySubdirName, newFileName)
                with open(fp, "r+") as f:
                    f.write("Some new modification")
            else:
                assert not "Unexpected value in whatIsDirty"

            assert(r.is_dirty())

            args = ["pull", d, "--inGit", rsrcType]

            wc = wavectl.Wavectl(
                designForTestArgv=args,
                designForTestRsrcs=rsrcs)

            self.assertRaisesRegexp(
                wavectl.PullError,
                (r"The path at .+ is dirty. "
                 r"Please commit your outstanding changes .*"),
                wc.runCmd)
Beispiel #6
0
    def executeCreate(self, rsrcType, target):
        """Call create call on target and return the generated output"""

        args = ["create", target,
                "--wavefrontHost", util.wavefrontHostName,
                "--apiToken", util.wavefrontApiToken] \
            + [rsrcType]
        wc = wavectl.Wavectl(designForTestArgv=args)

        with util.StdoutCapture() as captOut:
            wc.runCmd()

        return captOut.str()
Beispiel #7
0
    def repoDirIsFile(self, rsrcType, rsrcs):
        """ The passed repo dir exists but it is actually a file"""
        f = tempfile.NamedTemporaryFile(mode="w")

        # Deliberately pass a file name to the repoDir parameter
        args = ["pull", f.name, "--inGit", rsrcType]

        wc = wavectl.Wavectl(
            designForTestArgv=args,
            designForTestRsrcs=rsrcs)
        self.assertRaisesRegexp(
            wavectl.Error,
            "The given path: .+ is not a dir",
            wc.runCmd)
Beispiel #8
0
    def pushTargetDoesNotExist(self, rsrcType):
        """The push command is passed a target that does not exist.
        We expect an exception from the wavectl command"""

        nonExistingTarget = "someRandomPathDoesNotExist_lkjshfglkjdsfh"
        args = [
            "push",
            nonExistingTarget,
            "--inGit",
            rsrcType,
        ]
        wc = wavectl.Wavectl(designForTestArgv=args)

        self.assertRaisesRegexp(
            wavectl.Mutator.MutatorError,
            "The given path: .*" + nonExistingTarget + " does not exist",
            wc.runCmd)
Beispiel #9
0
    def executeShow(self,
                    rsrcType,
                    showAdditionalParams=[],
                    rsrcAdditionalParams=[]):
        """Execute a resource show command and return the printed std out."""

        args = ["show",
                "--wavefrontHost", util.wavefrontHostName,
                "--apiToken", util.wavefrontApiToken] \
            + showAdditionalParams \
            + [rsrcType] \
            + rsrcAdditionalParams
        wc = wavectl.Wavectl(designForTestArgv=args)

        with util.StdoutCapture() as captOut:
            wc.runCmd()

        return captOut.str()
Beispiel #10
0
    def executePull(
            self,
            rsrcType,
            dir,
            repo,
            expectedRsrcsInDir,
            pullAdditionalParams=[],
            rsrcAdditionalParams=[],
            additionalFileNames=[]):
        """ Execute a pull operation while some api functions are mocked."""

        logging.info("Starting executePull")

        args = ["pull",
                dir,
                "--wavefrontHost", wavefrontHostName,
                "--apiToken", wavefrontApiToken] \
            + pullAdditionalParams \
            + [rsrcType] \
            + rsrcAdditionalParams

        wc = wavectl.Wavectl(designForTestArgv=args)
        wc.runCmd()

        try:
            git.Repo(dir)
        except git.exc.InvalidGitRepositoryError as e:
            readmeFile = []
        else:
            readmeFile = ["README.md"]

        self.checkFilesInDir(
            rsrcType,
            expectedRsrcsInDir,
            dir,
            additionalFileNames=additionalFileNames + readmeFile)

        if repo:
            self.assertTrue(not repo.is_dirty(
                untracked_files=(len(additionalFileNames) == 0)))
            self.assertListEqual(sorted(repo.untracked_files),
                                 sorted(additionalFileNames))

        logging.info("Completed executePull")
Beispiel #11
0
    def test_apiTokenNotFound(self):
        """the api token is not specified. The config file is not populated and
        the command line ars do not have the --apiToken parameter. We expect
        an exception raised."""

        # The config file dir gets deleted. So the command cannot find the
        # desired config file
        d = tempfile.mkdtemp()
        shutil.rmtree(d, ignore_errors=True)

        args = ["show", "--wavefrontHost", "https://someHost.com", "alert"]
        # Since the designForTestRsrcs is not given, the command will try to
        # reach out to wavefront. It will look for the config file.
        wc = wavectl.Wavectl(designForTestArgv=args, designForTestConfigDir=d)

        self.assertRaisesRegexp(
            wavectl.ConfigError,
            ("The wavefront api token is not known. Either execute "
             "`wavectl config ...` or pass {0} command line option").format(
                 wc.pull.apiTokenOptionName), wc.runCmd)
Beispiel #12
0
    def tooManyRsrcsToDisplayInBrowser(self, rsrcType, rsrcs, maxBrowserTabs):
        """If we have too many selected rsrcs, displaying them in a
        browser should throw an exception saying that it is not allowed.
        This function checks for that error reporting"""

        with util.EnvModifier("MAX_BROWSER_TABS", maxBrowserTabs) as em:
            args = ["show", "--in-browser", rsrcType]
            wc = wavectl.Wavectl(designForTestArgv=args,
                                 designForTestRsrcs=rsrcs)

            # In this test we should attempt to open more tabs than allowed.
            # Checking that we are actually doing that.
            assert (len(rsrcs) > wc.show._maxBrowserTabs())

            # This show call prints a lot of lines to the output. Avoid the
            # print out by capturing the output
            with util.StdoutCapture() as capturedOut:
                self.assertRaisesRegexp(
                    wavectl.ShowError,
                    "Too many resources to display in browser.*", wc.runCmd)
Beispiel #13
0
    def pushTargetFileIsDirty(self, rsrcType):
        """Push is using one file to push. In a repo the pushed single file is
        dirty. Push should complain"""
        rt = util.resourceTypeFromString(rsrcType)

        with util.TempDir() as td:
            d = td.dir()
            r = self.repoInit(d)

            self.addReadmeFileToRepo(r)
            fileName = "newRsrc" + rt.fileExtension()
            self.addNewFileToRepo(r, fileName)

            args = ["push", os.path.join(d, fileName), "--inGit", rsrcType]

            wc = wavectl.Wavectl(designForTestArgv=args)

            self.assertRaisesRegexp(
                wavectl.MutatorError,
                (r"The path at .+ is dirty. "
                 r"Please commit your outstanding changes .*"), wc.runCmd)
Beispiel #14
0
    def test_wavefrontHostNotFound(self):
        """In this test the user attempts to execute a command that
        reaches out to the wavefront api server. However the config file
        mentioning the host name and the api token have not been initialized yet.
        The user also has not passed command line options specifying the wavefront
        host or the api token.  There should be a raised exception"""

        # The config file dir gets deleted. So the command cannot find the
        # desired config file
        d = tempfile.mkdtemp()
        shutil.rmtree(d, ignore_errors=True)

        args = ["show", "alert"]
        # Since the designForTestRsrcs is not given, the command will try to
        # reach out to wavefront. It will """
        wc = wavectl.Wavectl(designForTestArgv=args, designForTestConfigDir=d)

        self.assertRaisesRegexp(
            wavectl.ConfigError,
            ("The wavefront host url is not known. Either execute "
             "`wavectl config ...` or pass {0} command line option").format(
                 wc.pull.wavefrontHostOptionName), wc.runCmd)
Beispiel #15
0
    def repoIndexIsDirtyInUsedDir(self, cmd, rsrcType, rsrcs, error):
        """In this testcase, the repo has staged changes that have not been
        committed yet in the same dir as the pull/push dir. The command should
        not allow this to happen. We expect the initial branch to be without any
        outstanding modifications"""

        with TempDir() as td:
            d = td.dir()
            r = self.repoInit(d)

            self.addReadmeFileToRepo(r)
            self.addNewFileToRepo(r, "newFile")

            args = [cmd, d, "--inGit", rsrcType]

            wc = wavectl.Wavectl(designForTestArgv=args,
                                 designForTestRsrcs=rsrcs)

            self.assertRaisesRegexp(
                error, (r"The path at .+ is dirty. "
                        r"Please commit your outstanding changes .*"),
                wc.runCmd)