def testFailIfConnectionCannotBeMade(self):
        error = psycopg2.OperationalError()
        psycopg2.connect.side_effect = error

        main()

        self.module.fail_json.assert_called_with(msg='{}'.format(error))
    def testFailIfQueryThrowsAnError(self):
        error = psycopg2.ProgrammingError()
        self.cursor.fetchall.side_effect = error

        main()

        self.module.fail_json.assert_called_with(
            msg="Query failed: {}".format(error))
    def testExecutesTheQueryGiven(self):
        psycopg2.extras = MagicMock()
        psycopg2.extras.RealDictCursor = MagicMock()

        main()

        self.connection.cursor.assert_called_with(
            cursor_factory=psycopg2.extras.RealDictCursor)
        self.cursor.execute.assert_called_with(self.module.params['query'])
    def testConnectsToPostgresDatabaseWithParams(self):
        main()

        psycopg2.connect.assert_called_with(
            host=self.module.params['host'],
            database=self.module.params['database'],
            user=self.module.params['user'],
            password=self.module.params['password'],
            port=self.module.params['port'])
    def testReturnQueryResultsAndRowCount(self):
        for testCase in self.testCases:
            length = len(testCase)
            expectedResult = {'row_count': len(testCase), 'rows': testCase}
            self.cursor.fetchall = MagicMock(return_value=testCase)

            main()

            self.module.exit_json.assert_called_with(
                changed=True, ansible_module_results=expectedResult)
    def testAnsibleModuleIsCreated(self):
        main()

        basic.AnsibleModule.assert_called_with(
            argument_spec=self.postgresHandler.getArgumentSpec())