예제 #1
0
    def test_paginating_locations(self):
        names = []
        for i in range(12):
            names.append("Location #%s" % i)

        for n in names:
            Location.create(self.db, **{"name": n})

        page1 = Location.paged(self.db, 1, 10)
        page2 = Location.paged(self.db, 2, 10)

        assert_equal(names[0:10], map(lambda e: e.name.encode("ascii"), page1))
        assert_equal(names[10:12], map(lambda e: e.name.encode("ascii"), page2))
    def test_list_locations_ok_response(
            self, mock_location_controller_pagination_meta,
            mock_location_repo_fetch_all):
        '''Test fetch_all response.
        '''
        # Arrange
        with self.app.app_context():
            mock_location = Location(id=1,
                                     created_at=datetime.now(),
                                     updated_at=datetime.now(),
                                     name='Mock location',
                                     zone='Mock zone')
            mock_location_repo_fetch_all.return_value.items = [
                mock_location,
            ]
            mock_location_controller_pagination_meta.return_value = {
                'total_rows': 1,
                'total_pages': 1,
                'current_page': 1,
                'next_page': False,
                'prev_page': False
            }
            location_controller = LocationController(self.request_context)

            # Act
            result = location_controller.list_locations()

            # Assert
            assert result.status_code == 200
            assert result.get_json()['msg'] == 'OK'
예제 #3
0
    def test_create_order_when_date_booked_is_in_past(
            self, mock_current_time_by_zone, mock_get, mock_user_has_order,
            mock_request_params, mock_get_location, mock_user):
        '''Test create_date when the date booked is in the past.
        '''
        mock_user.return_value = {
            'id': '1',
            'mail': '*****@*****.**',
            'first_name': 'Joseph',
            'last_name': 'Serunjogi'
        }
        mock_get_location.return_value = Mock()
        mock_request_params.return_value = ('2019-02-01', 'web', 'lunch', [
            self.mock_meal_item,
        ], 1)
        mock_user_has_order.return_value = False
        mock_get.return_value = Location(id=1,
                                         created_at=datetime.now,
                                         updated_at=datetime.now(),
                                         is_deleted=False,
                                         name='mock',
                                         zone='+3')
        mock_current_time_by_zone.return_value = Mock()
        order_controller = OrderController(self.request_context)

        # Act
        result = order_controller.create_order()

        # Assert
        assert result.status_code == 400
        assert result.get_json()['msg'] == 'You are not allowed to book for ' \
            'a date in the past'
예제 #4
0
def load_location_table(data_path, location_file, systemname, dbfile):
    with DBSession(systemname, dbfile) as session, codecs.open(data_path + location_file, 'r',
                                                               encoding='ascii', errors='ignore') as f_handle:
        reader = csv.DictReader(f_handle)
        for item in reader:
            session.add(Location(**item))
        print("File_loaded...! {}".format(location_file))
예제 #5
0
    def test_create_order_ok_response(
        self,
        mock_order_controller_datetime,
        mock_create_order,
        mock_get_meals_by_ids,
        mock_datetime,
        mock_check_date_current_vs_date_for,
        mock_location_repo_get,
        mock_user_has_order,
        mock_request_params,
        mock_get_location,
        mock_auth_user
    ):
        '''Test create_order OK response.
        '''
        # Arrange
        with self.app.app_context():
            mock_order_controller_datetime.now = Mock(
                return_value=datetime(2019, 2, 13, 15, 0, 0)
            )
            mock_order_controller_datetime.strptime = Mock(
                return_value=datetime(2019, 2, 14, 13, 0, 0)
            )
            mock_datetime.utcnow = Mock(
                return_value=datetime(2019, 2, 13, 9, 0, 0)
            )
            mock_auth_user.return_value = {
                'id': 1,
                'mail': '*****@*****.**',
                'first_name': 'Joseph',
                'last_name': 'Serunjogi'
            }
            mock_get_location.return_value = 1
            mock_date_booked = Mock()
            mock_request_params.return_value = (
                mock_date_booked, 'web', 'lunch', [self.mock_meal_item, ], 1
            )
            mock_user_has_order.return_value = False
            mock_location_repo_get.return_value = Location(
                id=1,
                created_at=datetime.now,
                updated_at=datetime.now(),
                is_deleted=False,
                name='mock',
                zone='+3'
            )
            mock_check_date_current_vs_date_for.return_value = False
            mock_get_meals_by_ids.return_value = [self.mock_meal_item, ]
            mock_create_order.return_value = self.mock_order
            order_controller = OrderController(self.request_context)

            # Act
            result = order_controller.create_order()

            # Assert
            assert result.status_code == 201
            assert result.get_json()['msg'] == 'OK'
예제 #6
0
def create_location():
    name, slug = request.json['name'], request.json['slug']
    try:
        location = Location(name=name, slug=slug)
        db.session.add(location)
        db.session.commit()
    except IntegrityError:
        return error(Errors.SLUG_ALREADY_EXISTS_ERROR)
    return jsonify(location_schema.dump(location))
예제 #7
0
    def update_location(self, fields_map: Dict):
        new_location = Location()
        for k, v in fields_map.items():
            setattr(new_location, k, v)

        location_key = LocationKey(fields_map["block"], fields_map["road"],
                                   fields_map["postal_code"],
                                   fields_map["floor"], fields_map["unit"])

        setattr(new_location, 'is_shophouse', self.is_shophouse(location_key))
        return self.location_accessor.update(new_location, location_key)
예제 #8
0
def save_location():
    """添加省市区"""
    locations = location.get()
    print(locations)
    for item in locations:
        local = Location(code=item.get("code"),
                         name=item.get("name"),
                         provinceCode=item.get("provinceCode"),
                         cityCode=item.get("cityCode"))
        db.session.add(local)
    db.session.commit()
예제 #9
0
    def test_create_order_when_booked_late(
        self,
        mock_order_controller_datetime,
        mock_datetime,
        mock_check_date_current_vs_date_for,
        mock_location_repo_get,
        mock_user_has_order,
        mock_request_params,
        mock_get_location,
        mock_auth_user
    ):
        '''Testing create_order when booked late.
        '''
        # Arrange
        with self.app.app_context():
            mock_order_controller_datetime.now = Mock(
                return_value=datetime(2019, 2, 13, 15, 0, 0)
            )
            mock_order_controller_datetime.strptime = Mock(
                return_value=datetime(2019, 2, 14, 13, 0, 0)
            )
            mock_datetime.utcnow = Mock(
                return_value=datetime(2019, 2, 13, 16, 0, 0)
            )
            mock_auth_user.return_value = {
                'id': 1,
                'mail': '*****@*****.**',
                'first_name': 'Joseph',
                'last_name': 'Serunjogi'
            }
            mock_get_location.return_value = 1
            mock_request_params.return_value = (
                Mock(), 'web', 'lunch', [self.mock_meal_item, ], 1
            )
            mock_user_has_order.return_value = False
            mock_location_repo_get.return_value = Location(
                id=1,
                created_at=datetime.now,
                updated_at=datetime.now(),
                is_deleted=False,
                name='mock',
                zone='+3'
            )
            mock_check_date_current_vs_date_for.return_value = True
            order_controller = OrderController(self.request_context)

            # Act
            result = order_controller.create_order()

            # Assert
            assert result.status_code == 400
            assert result.get_json()['msg'] == 'It is too late to book a ' \
                'meal for the selected date '
예제 #10
0
파일: onetimes.py 프로젝트: sriram161/OR604
def load_location_table(data_path, location_file, systemname, dbfile):
    """ Loades Location table directoly from the zip as chunks into the sqlite database.
    """
    with DBSession(systemname,
                   dbfile) as session, codecs.open(
                       data_path + location_file,
                       'r',
                       encoding='ascii',
                       errors='ignore') as f_handle:
        reader = csv.DictReader(f_handle)
        for item in reader:
            session.add(Location(**item))
        print("File_loaded...! {}".format(location_file))
예제 #11
0
    def insert_location(self, fields_map: Dict):
        new_location = Location()
        for k, v in fields_map.items():
            setattr(new_location, k, v)

        location_key = LocationKey(fields_map["block"], fields_map["road"],
                                   fields_map["postal_code"],
                                   fields_map["floor"], fields_map["unit"])

        setattr(new_location, 'is_shophouse', self.is_shophouse(location_key))
        insert_location_id = self.location_accessor.insert(
            new_location, location_key)
        self.location_accessor.insert_has_land_use_type_relation(
            location_key, self.get_land_use_from_location(location_key))

        return insert_location_id
예제 #12
0
def convert_sqlocation2location(sq_location, user_skyquality):
    try:
        bortle = float(sq_location.bortle_scale)
        rating = round(10 - (bortle - 1))
    except ValueError:
        bortle = None
        rating = 5

    longitude = None
    latitude = None

    if sq_location.coords:
        longLat = sq_location.coords.split(',')
        if longLat and len(longLat) == 2:
            try:
                latitude = lonlat_parse(longLat[0])
                longitude = lonlat_parse(longLat[1])
            except ValueError:
                print('Unknown long-lat format=' + sq_location.coords)
                return None

    is_for_observation = not any(x in sq_location.accessibility
                                 for x in ['nevhodné', 'nepřístupné'])

    loc = Location(
        name=sq_location.name,
        longitude=longitude,
        latitude=latitude,
        descr=sq_location.descr,
        bortle=bortle,
        rating=rating,
        #  sql_readings = db.relationship('SqlReading', backref='location', lazy=True)
        country_code='CZ',
        user_id=None,
        is_public=True,
        is_for_observation=is_for_observation,
        origin_id=SKYQ_ORIGIN_ID_PREFIX + str(sq_location.location_id),
        create_by=user_skyquality.id,
        update_by=user_skyquality.id,
        create_date=datetime.now(),
        update_date=datetime.now(),
    )

    return loc
    def test_get_location_ok_response(self, mock_location_repo_get):
        '''Test get_location OK response.
        '''
        # Arrange
        with self.app.app_context():
            mock_location = Location(id=1,
                                     created_at=datetime.now(),
                                     updated_at=datetime.now(),
                                     name='Mock location',
                                     zone='Mock zone')
            mock_location_id = 1
            mock_location_repo_get.return_value = mock_location
            location_controller = LocationController(self.request_context)

            # Act
            result = location_controller.get_location(mock_location_id)

            # Assert
            assert result.status_code == 200
            assert result.get_json()['msg'] == 'OK'
예제 #14
0
    def __init__(self, timestamp: int, vehicle_id: str, event_type: str,
                 lat: float, long: float, user_id: int, session: Session):

        # Format input vars
        self._timestamp = int(timestamp)
        self._event_type = EventType[event_type]
        self._lat = float(lat)
        self._long = float(long)
        self._user_id = (None if user_id == 'NULL' else int(user_id))
        self._session = session

        # Set User
        self.user = DBOperations.find_or_initialize_by(self._session, User,
                                                       **{'id': self._user_id})

        # Set Location
        self.location = Location(lat=self._lat, long=self._long)

        # Set Vehicle
        self.vehicle = DBOperations.find_or_initialize_by(
            self._session, Vehicle, **{'id': vehicle_id})
        self.vehicle.update_location(self._event_type, self.location)

        # Set Event
        self.event = Event(
            type=self._event_type,
            timestamp=self._timestamp,
            location=self.location,
            vehicle=self.vehicle,
        )

        # Set Ride
        self.ride = None
        if self.event.type is EventType.START_RIDE:
            self.ride = Ride(self.user, self.vehicle, self.event)
        elif self.event.type is EventType.END_RIDE:
            self.ride = self.user.rides[-1]
            self.ride.end_ride(self.event)
    def test_create_location_ok_response(
            self, mock_location_repo_new_location,
            mock_location_controller_request_params):
        '''Test create_location OK response.
        '''
        # Arrange
        with self.app.app_context():
            mock_location = Location(id=1,
                                     created_at=datetime.now(),
                                     updated_at=datetime.now(),
                                     name='Mock location',
                                     zone='Mock zone')
            mock_name = 'Mock name'
            mock_zone = 'Mock zone'
            mock_location_repo_new_location.return_value = mock_location
            mock_location_controller_request_params.return_value = mock_name, mock_zone
            location_controller = LocationController(self.request_context)

            # Act
            result = location_controller.create_location()

            # Assert
            assert result.status_code == 201
            assert result.get_json()['msg'] == 'OK'
예제 #16
0
파일: company.py 프로젝트: viaict/viaduct
def create(company_id=None):
    # Select company.
    if company_id:
        company = Company.query.get_or_404(company_id)
    else:
        company = Company()

    data = {}

    data["name"] = company.name
    data["description"] = company.description
    data["contract_start_date"] = company.contract_start_date
    data["contract_end_date"] = company.contract_end_date
    data["website"] = company.website

    # Select locations.
    if company.location_id:
        location = Location.query.get(company.location_id)
    else:
        location = Location()

    data['location_city'] = location.city
    data['location_country'] = location.country
    data['location_address'] = location.address
    data['location_zip'] = location.zip
    data['location_postoffice_box'] = location.postoffice_box
    data['location_email'] = location.email
    data['location_phone_nr'] = location.phone_nr

    if company.contact_id:
        contact = Contact.query.get(company.contact_id)
    else:
        contact = Contact()

    data['contact_name'] = contact.name
    data['contact_email'] = contact.email
    data['contact_phone_nr'] = contact.phone_nr

    form = init_form(NewCompanyForm, data=data)

    if form.validate_on_submit():

        if not contact.id and Contact.query.filter(
                Contact.name == form.contact_name.data).count():
            flash(_('Contact name "%s" is already in use.' %
                    form.contact_name.data), 'danger')
            return render_template('company/create.htm', company=company,
                                   form=form)
        if not contact.id and Contact.query.filter(
                Contact.email == form.contact_email.data).count():
            flash(_('Contact email "%s" is already in use.' %
                    form.contact_email.data), 'danger')
            return render_template('company/create.htm', company=company,
                                   form=form)
        contact.name = form.contact_name.data
        contact.email = form.contact_email.data
        contact.phone_nr = form.contact_phone_nr.data
        # Create or update to contact
        db.session.add(contact)
        db.session.commit()

        # Create or update to location
        location.city = form.location_city.data
        location.country = form.location_country.data
        location.address = form.location_address.data
        location.zip = form.location_zip.data
        location.postoffice_box = form.location_postoffice_box.data
        location.email = form.location_email.data
        location.phone_nr = form.location_phone_nr.data
        db.session.add(location)
        db.session.commit()

        #
        if not company.id and Company.query.filter(
                Company.name == form.name.data).count():
            flash(_('Name "%s" is already in use.' % form.name.data),
                  'danger')
            return render_template('company/edit.htm', company=company,
                                   form=form)
        company.name = form.name.data
        company.description = form.description.data
        company.contract_start_date = form.contract_start_date.data
        company.contract_end_date = form.contract_end_date.data
        company.location = location
        company.contact = contact
        company.website = form.website.data
        if request.files['file']:
            logo = request.files['file']
            _file = file_service.add_file(FileCategory.COMPANY_LOGO,
                                          logo, logo.filename)
            company.logo_file = _file

        db.session.add(company)
        db.session.commit()
        flash(_('Company "%s" saved.' % company.name), 'success')
        return redirect(url_for('company.view', company_id=company.id))
    else:
        flash_form_errors(form)

    return render_template('company/create.htm', company=company, form=form)
예제 #17
0
 def test_end_location(self):
     test_end_location = Location(7, 91)
     ride = self.session.query(Ride).all()[0]
     self.assertEqual(ride.end_location.lat, test_end_location.lat)
     self.assertEqual(ride.end_location.long, test_end_location.long)
예제 #18
0
 def test_start_location(self):
     test_start_location = Location(33, -87)
     ride = self.session.query(Ride).all()[0]
     self.assertEqual(ride.start_location.lat, test_start_location.lat)
     self.assertEqual(ride.start_location.long, test_start_location.long)
예제 #19
0
    def create_location(self, location_code, location):
        location = Location(location_code=location_code, location=location)

        location.save()
        return location
예제 #20
0
파일: server.py 프로젝트: worace/hfa_events
def show_locations():
    return jsonify(map(lambda location: location.serialize(),
                       Location.paged(db(), page_number(request))))
예제 #21
0
파일: server.py 프로젝트: worace/hfa_events
def create_location():
    loc = Location.create(db(), **request.json)
    return jsonify({"success": True,
                    "location": loc.serialize()})
예제 #22
0
 def new_location(self, name, zone):
     location = Location(name=name, zone=zone)
     location.save()
     return location
예제 #23
0
파일: server.py 프로젝트: worace/hfa_events
def show_location(location_id):
    loc = Location.find(db(), location_id)
    return jsonify(loc.serialize())
예제 #24
0
 def test_get_distance(self):
     start_location = Location(33, -87)
     end_location = Location(7, 91)
     distance = Location.get_distance(start_location, end_location)
     self.assertEqual(distance, 15572131.792956578)
예제 #25
0
def location():
    with open('tests/demo_geocode_data.json') as file_object:
        contents = json.load(file_object)

    return Location.instantiate_location(contents, 'newhalem')
예제 #26
0
 def test_limit(self):
     start_location = Location(-100, 190)
     self.assertEqual(start_location.lat, -90)
     self.assertEqual(start_location.long, 180)