Beispiel #1
0
    def test_confirmation_receiver_JSON_failure(self):
        """
        This method tests the confirmation receiver JSON view of the confirmation page. The expected result of this
        test is for the session to have already been added to the database and to fail to be added again.
        """
        # Add pattern and time to database
        time = datetime.datetime.now().replace(minute=5, second=0, microsecond=0) + datetime.timedelta(days=1)
        with transaction.manager:
            DBSession.add(Run(create_input_pattern(), time, ""))
            DBSession.commit

        # Set up request
        request = DummyRequest(route='/confirm.json')
        request.session["pattern"] = create_input_pattern()
        request.session["viewing_date"] = time.strftime("%d/%m/%Y")
        request.session["viewing_hour"] = time.strftime("%H")
        request.session["viewing_slot"] = time.strftime("%M")

        response_dict = confirmation_receiver_JSON(request)

        # Test response has arrived
        assert response_dict
        # Assert that the data was not successfully stored.
        assert not response_dict["success"]
        # Assert that the response has been given a failure message.
        assert response_dict["failure_message"]

        # Assert that the session still exists.
        assert not "pattern" in request.session
        assert not "viewing_date" in request.session
        assert not "viewing_hour" in request.session
        assert not "viewing_slot" in request.session
Beispiel #2
0
    def test_run_get_time_slots_for_day_with_runs(self):
        """
        This method tests the ability of the runs table to retrieve the available time slots in a given day. The
        expected result of this test is for the number of retrieved time slots to be equal to the number of five
        minute time slots in a day minus two (for two runs).
        """
        # Give the method a future date and receive correct no. of time-slots for that date
        date = datetime.date.today() + datetime.timedelta(days=2)

        min_time = project_config["starting_time"]
        max_time = project_config["closing_time"]
        # Calculate the no. of hours in a given day to test
        no_mins = (max_time.hour*60 + max_time.minute) - (min_time.hour*60 + min_time.minute)
        no_time_slots = math.ceil(no_mins / 5)

        date = datetime.datetime.combine(date, datetime.time(hour=12, minute=0, second=0, microsecond=0))

        runs = [
            Run(create_input_pattern(), date, self._insert_name),
            Run(create_input_pattern(), date + datetime.timedelta(minutes=5), self._insert_name)]
        with transaction.manager:
            DBSession.add_all(runs)
            DBSession.commit

        time_slots = Run.get_time_slots_for_day(date, datetime.datetime.now())

        # Assert that the correct number of available time slots have been retrieved.
        assert no_time_slots - len(runs) == len(time_slots)
Beispiel #3
0
    def test_time_slot_receiver_JSON_runs(self):
        """
        This method tests the time slot receiver JSON view when there are runs in the server-side database. The
        expected result of this pattern is for the correct JSON response to be retrieved.
        """
        request = DummyRequest(route='/scheduler.json')

        if project_config["start_date"]:
            input_date = datetime.datetime.combine(project_config["start_date"], datetime.time())
        else:
            input_date = datetime.datetime.today() + datetime.timedelta(hours=1)

        user_input = int(time.mktime(input_date.timetuple()) * 1000)

        request.content_type = "application/json"
        request.POST["date"] = str(user_input)

        # Insert runs that will the next hour with even minutes that are a multiple of 10
        with transaction.manager:
            runs = []
            for minutes in range(0, 60, 10):
                runs.append(Run(create_input_pattern(), datetime.datetime(input_date.year, input_date.month,
                                                                          input_date.day, input_date.hour, minutes), ""))
            DBSession.add_all(runs)
            DBSession.commit()

        response = time_slot_reciever_JSON(request)

        # Assert that a response has been received.
        assert response

        response_dict = eval(str(response))
        for min in range(0, 60, 10):
            # Assert that the given slot is not in the response (means there is a run at this point)
            assert min not in response_dict[input_date.hour]
def setup_module(self):
    """
    Setup data that will be needed throughout the class and setup database
    """
    self.config = testing.setUp()
    engine = create_engine("sqlite:///testdb.sqlite")
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
 def test_insert(self):
     '''
     Test insertion of data into the runs table
     '''
     with transaction.manager:
         run = Run(create_input_pattern(), datetime.datetime.now(), self._insert_name)
         DBSession.add(run)
         DBSession.commit()
Beispiel #6
0
 def setup_class(self):
     """
     This method sets up the class for testing, storing shared that data that will be used in multiple tests.
     """
     self.config = testing.setUp()
     engine = create_engine('sqlite:///testdb.sqlite')
     DBSession.configure(bind=engine)
     Base.metadata.create_all(engine)
Beispiel #7
0
 def test_insert(self):
     """
     This method tests the ability of the runs table to insert a new row. The expected result of this test is for
     a row to be inserted into the table correctly.
     """
     with transaction.manager:
         run = Run(create_input_pattern(), datetime.datetime.now(), self._insert_name)
         DBSession.add(run)
         DBSession.commit()
 def setup_class(self):
     '''
     Setup data that will be needed throughout the class and setup database
     '''
     self._insert_name = str(time.time())
     
     self.config = testing.setUp()
     engine = create_engine('sqlite:///testdb.sqlite')
     DBSession.configure(bind=engine)
     Base.metadata.create_all(engine)
Beispiel #9
0
 def setup_class(self):
     """
     This method sets up the testing class, initialising shared data that will be needed during testing.
     """
     self._insert_name = str(time.time())
     
     self.config = testing.setUp()
     engine = create_engine('sqlite:///testdb.sqlite')
     DBSession.configure(bind=engine)
     Base.metadata.bind = engine
     Base.metadata.create_all(engine)
Beispiel #10
0
def main(argv=sys.argv):
    """
    Initialise the database if this module is called from the command line or external software.

    @param argv The system arguments from the command line or external software.
    """
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        pass
Beispiel #11
0
    def get_unsent_runs(cls, min_time):
        """
        This method retrieves all of the currently unsent patterns in the database that are set to occur after the
        given minimum time.

        @param min_time The time after which the database should be query.

        @return unsent_runs The runs that have not yet been sent to the Raspberry Pi.
        """
        with transaction.manager:
            unsent_runs = DBSession.query(Run).filter(and_(Run.time_slot > min_time, Run.sent == False)).all()

            for run in unsent_runs:
                run.sent = True

            DBSession.commit()

        return unsent_runs
Beispiel #12
0
    def test_run_get_runs_for_day_with_runs(self):
        """
        This method tests the ability of the runs table to retrieve every run set to be played on a given day. The
        expected result should be for the call to result in the same number of runs as previously added.
        """
        dt = datetime.datetime.now() + datetime.timedelta(days=1)
        dt = dt.replace(minute=0, second=0, microsecond=0)

        runs = [
            Run(create_input_pattern(), dt, self._insert_name),
            Run(create_input_pattern(), dt + datetime.timedelta(minutes=5), self._insert_name)]
        with transaction.manager:
            DBSession.add_all(runs)
            DBSession.commit

        date = datetime.date.today() + datetime.timedelta(days=1)
        dayRuns = Run.get_runs_for_day(date)
        # Assert that the correct number of runs have been retrieved
        assert dayRuns == runs
Beispiel #13
0
    def get_run_for_time_slot(cls, time_slot):
        """
        @param time_slot The time slot the database should query for a run.

        @return The run that occupies the specified time slot if one exists, otherwise None.

        Returns a run if it exists for the given time slot otherwise
        return None
        """
        return DBSession.query(Run).filter(Run.time_slot == time_slot).all()
Beispiel #14
0
 def test_query(self):
     """
     This method tests the ability of the runs table to retrieve data from the runs table. The expected result of
     this is for a row to be retrieved from the table correctly.
     """
     # Test logic works
     assert DBSession.query(Run).filter(Run.user_name==self._insert_name).all()
     
     # Test logic works as expected (Grid object is not altered in any way)
     for row in DBSession.query(Run).filter(Run.user_name==self._insert_name).all():
         returned_pattern = row.input_pattern.split('\n')
         test_pattern = create_input_pattern().split('\n')
         for x, row in enumerate(test_pattern):
             # For each row of the pattern
             for y, col in enumerate(row):
                 if test_pattern[x][y] == '*':
                     # Assert that the retrieved pattern and the test pattern match at these 'coordinates'.
                     assert returned_pattern[x][y] == '*'
                 else:
                     # Assert that the retrieved pattern and the test pattern match at these 'coordinates'.
                     assert returned_pattern[x][y] == '-'           
def test_run_transmitter_view():
    """
    This function tests the functionality of the run_transmitter view. The expected result of this
    test is that the view functions correctly and retrieves currently unsent runs for the raspberry pi.
    """
    time_slot = datetime.datetime.now() + datetime.timedelta(days=5)

    # Add a pattern and time to the database for testing
    with transaction.manager:
        DBSession.add(Run(create_input_pattern(), time_slot, ""))
        DBSession.commit()

    # Set up request
    request = DummyRequest(route="/run_transmitter.json")
    time_slot -= datetime.timedelta(hours=1)
    request.POST["min_time"] = time_slot.isoformat()

    # Call the view
    response = run_transmitter_view(request)

    # Test that the view has returned a response
    assert response
Beispiel #16
0
    def insert_run(cls, pattern, time_slot):
        """
        Ensures that the pattern and time_slot meet validation
        and inserts the run into the run table.

        This method ensures that the pattern and time slot meet validation before inserting the run into the runs table
        of the server-side database.

        @param pattern The pattern to input into the table.
        @param time_slot The datetime at which the pattern should be run.
        """
        now = datetime.datetime.now()

        # Perform validation checks
        cls._validate_time_slot(now, time_slot)
        if cls.get_run_for_time_slot(time_slot):
            raise RunSlotTakenError("Time slots already has a run associated")

        # Insert pattern and time slot into database
        with transaction.manager:
            DBSession.add(Run(pattern, time_slot, ""))
            DBSession.commit()
Beispiel #17
0
    def test_run_get_unsent_runs(self):
        """
        This method tests the ability of the runs table to retrieve the runs than have not yet been sent to the
        raspberry pi. The expected result of this test is that the unsent runs can be correctly retrieved.
        """

        time_slot = datetime.datetime.now() + datetime.timedelta(days=35)

        # Create some runs to go into the table
        runs = [
            Run(create_input_pattern(), time_slot, self._insert_name),
            Run(create_input_pattern(), time_slot + datetime.timedelta(minutes=5), self._insert_name),
            Run(create_input_pattern(), time_slot + datetime.timedelta(minutes=10), self._insert_name)
        ]

        # Add runs to table
        with transaction.manager:
            DBSession.add_all(runs)
            DBSession.commit()

        new_sent_runs = Run.get_unsent_runs(time_slot - datetime.timedelta(minutes=5))

        # Assert that the collected runs have been retrieved
        assert new_sent_runs
        # Assert that the list of sent runs contains the correct number of runs
        assert len(new_sent_runs) == 3

        # Create some more runs to go into the table
        new_runs = [
            Run(create_input_pattern(), time_slot + datetime.timedelta(minutes=15), self._insert_name),
            Run(create_input_pattern(), time_slot + datetime.timedelta(minutes=20), self._insert_name),
            Run(create_input_pattern(), time_slot + datetime.timedelta(minutes=25), self._insert_name)
        ]

        # Add these runs to the table
        with transaction.manager:
            DBSession.add_all(new_runs)
            DBSession.commit()

        new_sent_runs = Run.get_unsent_runs(time_slot - datetime.timedelta(minutes=5))

        # Assert that the collected runs have been retrieved
        assert new_sent_runs
        # Assert that the list of sent runs still contains the correct number of runs
        assert len(new_sent_runs) == 3
Beispiel #18
0
    def teardown_class(self):
        """
        This method tears down the class after testing has been completed, in order to ensure no data exists after
        testing that shouldn't. In this case, closes down the database session.
        """
        with transaction.manager:
            for run in DBSession.query(Run).all():
                # Delete all runs in the database.
                DBSession.delete(run)
            DBSession.commit()

        # Close the database session.
        DBSession.remove()
        testing.tearDown()
Beispiel #19
0
    def teardown_class(self):
        """
        This method tears down the testing logic to ensure that no data remains after testing that shouldn't. In this
        case, it closes the database session.
        """
        with transaction.manager:
            for run in DBSession.query(Run).all():
                # Delete every run in the session.
                DBSession.delete(run)
            DBSession.commit()

        # Close the session.
        DBSession.remove()
        testing.tearDown()
Beispiel #20
0
    def get_runs_for_day(cls, date):
        """
        This method retrieves every run set to take place on the given data.

        @param date The date for which the runs to take place should be retrieved.

        @return The runs set to take place for the day.
        """
        now = datetime.datetime.now()
        start = date
        end = date + datetime.timedelta(days=1)

        # Query the runs that are happening at this hour
        run_times = (
            DBSession.query(Run).filter(and_(Run.time_slot < end, Run.time_slot >= start, Run.time_slot > now)).all()
        )

        return run_times
Beispiel #21
0
 def test_delete(self):
     '''
     Test run deletion
     '''
     # Delete the run inserted by this test
     runs = DBSession.query(Run).filter(Run.user_name==self._insert_name)
     assert runs.all()
     for run in runs:
         DBSession.delete(run)
         DBSession.commit()
         
     # Ensure deletion
     runs = DBSession.query(Run).filter(Run.user_name==self._insert_name)
     assert not runs.all()
Beispiel #22
0
    def test_delete(self):
        """
        This method tests the ability of the runs table to delete data from it. The expected result of this is for the
        data to be correctly deleted from the table.
        """
        # Delete the run inserted by this test
        runs = DBSession.query(Run).filter(Run.user_name==self._insert_name)
        # Assert that the runs have been retrieved
        assert runs.all()
        for run in runs:
            DBSession.delete(run)
            DBSession.commit()

        runs = DBSession.query(Run).filter(Run.user_name==self._insert_name)
        # Assert that the selected runs have been deleted.
        assert not runs.all()
Beispiel #23
0
 def test_query(self):
     '''
     Test querying of data from the runs table
     '''
     assert DBSession.query(Run).filter(Run.user_name==self._insert_name).all()
Beispiel #24
0
 def teardown_class(self):
     """
     This method tears down the testing class, closing the database session once the class is redundant.
     """
     DBSession.remove()
     testing.tearDown()
Beispiel #25
0
 def teardown_class(self):
     '''
     Closes database session once the class is redundant
     '''
     DBSession.remove()
     testing.tearDown()