def test_get_reservations(self): customer = Customer(name='Teemu Teekkari', email='teemu.teekkari@aalto fi') service1 = Service(name='service1', price=10.0, duration=60.0, description='service1 description') service2 = Service(name='service1', price=10.0, duration=60.0, description='service1 description') self.db.save(service1) self.db.save(service2) added_reservations = [] date = QtCore.QDate.currentDate() resource = Resource(name="Resource1", resource_type="ROOM") for x in range(8, 19): start_time = QtCore.QTime(x, 0) end_time = QtCore.QTime(x, 59) start = QtCore.QDateTime(date, start_time) end = QtCore.QDateTime(date, end_time) new_reservation = Reservation(customer=customer, resource=resource, start=start, end=end, services=[service1, service2]) self.db.save(new_reservation) added_reservations.append(new_reservation) reservations = self.db.get_reservations() for i in range(len(reservations)): self.assertEqual(reservations[i], added_reservations[i])
def test_models(self): #Create a Table and a Waiter table = Table(table_no="table1") db.session.add(table) table2 = Table(table_no="table2") db.session.add(table2) table3 = Table(table_no="table3") db.session.add(table3) table4 = Table(table_no="table4") db.session.add(table4) table5 = Table(table_no="table4") db.session.add(table4) waiter = Waiter(name="Juan") db.session.add(waiter) db.session.commit() service = Service(tip=90.80) db.session.add(service) db.session.commit() service = Service(tip=90.80) db.session.add(service) db.session.commit() service = Service(tip=90.80) db.session.add(service) db.session.commit() service = Service(tip=90.80) db.session.add(service) db.session.commit() try: service = Service(tip=90.80) except Exception: pass
def test_get_services(self): service1 = Service(name='service1', price=10.0, duration=60.0, description='service1 description') service2 = Service(name='service1', price=10.0, duration=60.0, description='service1 description') self.db.save(service1) self.db.save(service2) services = self.db.get_services() self.assertEqual(services, [service1, service2])
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): """ Create a service from an endpoint if it does not already exists. """ from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: # check if endpoint is valid request = requests.get(endpoint) if request.status_code == 200: LOGGER.debug('Creating a %s service for endpoint=%s catalog=%s' % (service_type, endpoint, catalog)) service = Service(type=service_type, url=endpoint, title=title, abstract=abstract, csw_type='service', catalog=catalog) service.save() return service else: LOGGER.warning('This endpoint is invalid, status code is %s' % request.status_code) else: LOGGER.warning( 'A service for this endpoint %s in catalog %s already exists' % (endpoint, catalog)) return None
def import_services(service_list): """Add any services from file to django database""" current_services = read_current_services() for service in service_list: if service not in current_services: new_service = Service(service_name=service) new_service.save()
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None): """ Create a service from an endpoint if it does not already exists. """ from models import Service if Service.objects.filter(url=endpoint).count() == 0: # check if endpoint is valid request = requests.get(endpoint) if request.status_code == 200: print 'Creating a %s service for endpoint %s' % (service_type, endpoint) service = Service(type=service_type, url=endpoint, title=title, abstract=abstract) service.save() return service else: print 'This endpoint is invalid, status code is %s' % request.status_code else: print 'A service for this endpoint %s already exists' % endpoint return None
def service_add(request, response_format='html'): "Service add" if not request.user.profile.is_admin('anaf.services'): return user_denied( request, message= "You don't have administrator access to the Service Support module" ) if request.POST: if 'cancel' not in request.POST: service = Service() form = ServiceForm(request.user.profile, request.POST, instance=service) if form.is_valid(): service = form.save() service.set_user_from_request(request) return HttpResponseRedirect( reverse('services_service_view', args=[service.id])) else: return HttpResponseRedirect(reverse('services')) else: form = ServiceForm(request.user.profile) context = _get_default_context(request) context.update({'form': form}) return render_to_response('services/service_add', context, context_instance=RequestContext(request), response_format=response_format)
def service_add_post(): from flask import request messages = session["messages"] user_id = messages[messages.index(":")+1:len(messages)-1] user = User.query.filter_by(id=user_id).first() name = user.first_name + " " + user.last_name title = request.form["title"] price = float(request.form["price"]) desc = request.form["desc"] category = request.form["category"] address = request.form["address"] file = request.files["file"] requested_by = user_id request = int(request.form["request_service"]) try: id_num = Service.query.all()[-1].id + 1 except: id_num = 0 ext_index = file.filename.rfind(".") ext = file.filename[ext_index:] filename = str(str(id_num) + ext).upper() file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) s = Service(title, price, desc, category, address, requested_by, request, filename) db_session.add(s) db_session.commit() return redirect("/home/All")
def setUp(self): super(HistoryTest, self).setUp() Status.load_defaults() self.service = Service(slug="account", name="Account", description="The BEST SERVICE") self.service.put()
def populate_initial_services(): """ Populate a fresh installed Hypermap instances with basic services. """ services_list = ( ('Harvard WorldMap', 'Harvard WorldMap open source web geospatial platform', 'Hypermap:WorldMap', 'http://worldmap.harvard.edu'), ('NYPL MapWarper', 'The New York Public Library (NYPL) MapWarper web site', 'Hypermap:WARPER', 'http://maps.nypl.org/warper/maps'), ('Map Warper', 'The MapWarper web site developed, hosted and maintained by Tim Waters', 'Hypermap:WARPER', 'http://mapwarper.net/maps'), ('WorldMap Warp', 'The MapWarper instance part of the Harvard WorldMap project', 'Hypermap:WARPER', 'http://warp.worldmap.harvard.edu/maps'), ('WFP GeoNode', 'World Food Programme GeoNode', 'OGC:WMS', 'http://geonode.wfp.org/geoserver/ows?'), ('NASA EARTHDATA', 'NASA EARTHDATA, powered by EOSDIS', 'OGC:WMTS', 'http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml' ), ) esri_endpoint = 'https://gis.ngdc.noaa.gov/arcgis/rest/services' print '*** Importing esri endpoint: %s' % esri_endpoint create_services_from_endpoint(esri_endpoint) for service in services_list: print '*** Importing %s' % service[0] service = Service(title=service[0], abstract=service[1], type=service[2], url=service[3]) service.save()
def create_service(jwt): body = request.get_json() try: name = body.get('name', None) type = body.get('type', None) address = body.get('address', None) region_id = body.get('region_id', None) email = body.get('email', None) phone = body.get('phone', None) website = body.get('website', None) image = body.get('image', None) if (name is None) or (type is None) or (address is None) or ( region_id is None): abort(422) new_service = Service(name=name, type=type, address=address, region_id=region_id, email=email, phone=phone, website=website, image=image) new_service.insert() return jsonify({'success': True, 'created': new_service.id}), 200 except BaseException: print(sys.exc_info()) abort(422)
def post(self, version): if not self.valid_version(version): self.error(404, "API Version %s not supported" % version) return name = self.request.get('name', default_value=None) description = self.request.get('description', default_value=None) if not name or not description: self.error(400, "Bad Data: Name: %s, Description: %s" \ % (name, description)) return slug = slugify.slugify(name) existing_s = Service.get_by_slug(slug) if existing_s: self.error(404, "A sevice with this name already exists") return s = Service(name=name, slug=slug, description=description) s.put() invalidate_cache() self.response.set_status(201) self.json(s.rest(self.base_url(version)))
def post(self, version): logging.debug("ServicesListHandler#post") if (self.valid_version(version)): name = self.request.get('name', default_value=None) description = self.request.get('description', default_value=None) if name and description: slug = slugify.slugify(name) existing_s = Service.get_by_slug(slug) # Update existing resource if existing_s: existing_s.description = description existing_s.put() self.json(existing_s.rest(self.base_url(version))) # Create new service else: s = Service(name=name, slug=slug, description=description) s.put() self.json(s.rest(self.base_url(version))) else: self.error( 400, "Bad Data: Name: %s, Description: %s" % (name, description)) else: self.error(404, "API Version %s not supported" % version)
def serviceDel(): uid = request.args.get('id', '') _service = Service() if _service.del_service(uid): return redirect('/services/') else: return '域名管理信息删除失败!'
def test_service_creation(self): service = Service(name='service1', price=10.0, duration=60.0, description='service1 description') self.db.save(service) service_from_db = self.db.services.get_by_id(service.ID) self.assertEqual(service, service_from_db)
def get_all(self): services = [] self.cursor.execute( 'SELECT * FROM services ORDER BY name COLLATE NOCASE') rows = self.cursor.fetchall() for row in rows: services.append(Service(row=row)) return services
def service_create(): name = request.form.get('name', '').strip() icon = request.form.get('icon', '').strip() if not name: return Error.ARGUMENT_MISSING('name') srv = Service(name, icon) db.session.add(srv) db.session.commit() return jsonify({"service": srv.as_dict(True)})
def setUp(self): super(ServiceListInstanceTest, self).setUp() self.service_list = List(slug="foo", name="Foo", description="Bar") self.service_list.put() self.service = Service(list=self.service_list, name="Foo", slug="foo", description="foo") self.service.put()
def accept(self): name = self.name.text() price = self.price.value() duration = self.duration.value() description = self.description.toPlainText() if name: if self.service: service = Service(ID=self.service.ID, name=name, price=price, duration=duration, description=description) else: service = Service(name=name, price=price, duration=duration, description=description) self.database.save(service) self.information = MessageDialog("Service added", icon=QtWidgets.QMessageBox.Information) self.information.show() self.close() self.parent.update() else: self.information = MessageDialog("Please fill in name.") self.information.show()
def update_service(): params = request.args if request.method == 'GET' else request.form _id = params.get('id', '') _url = params.get('url', '') _username = params.get('username', '') _password = params.get('password', '') _func = params.get('func', '') _service = Service() _is_ok = _service.update_service(_url, _username, _password, _func, _id) return json.dumps({'is_ok': _is_ok})
def service_create(): name = request.form.get('name', '').strip() icon = request.form.get('icon', '').strip() encrypted = request.form.get('encrypted', '').strip().lower() in ("1", "true", "yes") if not name: return jsonify(Error.ARGUMENT_MISSING('name')) srv = Service(name, icon, encrypted=encrypted) db.session.add(srv) db.session.commit() return jsonify({"service": srv.as_dict(True)})
def add_service(user: User, service_name, service_username, service_password): f = Fernet(user.key) service = Service( user_id=user.id, service_name=service_name, username=service_username, password_hash=f.encrypt(service_password.encode()).decode() ) session.add(service) session.commit()
def handle_service(): service1=request.get_json() if service1 is None: raise APIException ("You need to specify the request body as a json object ", status_code=400) if "servicetype_name" not in service1: raise APIException ("You need to specify servicetype_name", status_code=400) sercice2=Service(servicetype_name=service1["servicetype_name"]) db.session.add(sercice2) db.session.commit() return "services created successfully"
def setUp(self): self.group, created = Group.objects.get_or_create(name='test') self.user, created = DjangoUser.objects.get_or_create( username=self.username) self.user.set_password(self.password) self.user.save() perspective, created = Perspective.objects.get_or_create( name='default') perspective.set_default_user() perspective.save() ModuleSetting.set('default_perspective', perspective.id) self.contact_type = ContactType(name='test') self.contact_type.set_default_user() self.contact_type.save() self.contact = Contact(name='test', contact_type=self.contact_type) self.contact.set_default_user() self.contact.save() self.status = TicketStatus(name='TestStatus') self.status.set_default_user() self.status.save() self.queue = TicketQueue(name='TestQueue', default_ticket_status=self.status) self.queue.set_default_user() self.queue.save() self.ticket = Ticket(name='TestTicket', status=self.status, queue=self.queue) self.ticket.set_default_user() self.ticket.save() self.agent = ServiceAgent(related_user=self.user.profile, available_from=datetime.time(9), available_to=datetime.time(17)) self.agent.set_default_user() self.agent.save() self.service = Service(name='test') self.service.set_default_user() self.service.save() self.sla = ServiceLevelAgreement(name='test', service=self.service, client=self.contact, provider=self.contact) self.sla.set_default_user() self.sla.save()
def test_msnp_commands(): user_service = UserService() auth_service = AuthService() nb = NB(user_service, auth_service, [Service('0.0.0.0', 0)]) sb = SB(user_service, auth_service) # User 1 login nc1 = NBConn(nb, MSNPWriter()) user1 = _login_msnp(nc1, '*****@*****.**') nc1._l_adc(1, 'FL', '[email protected]', 'F=Test2') nc1.writer.pop_message('ADC', 1, 'FL', '[email protected]', ANY) # User 2 login nc2 = NBConn(nb, MSNPWriter()) user2 = _login_msnp(nc2, '*****@*****.**') nc1.writer.pop_message('NLN', 'NLN', '*****@*****.**', ANY, ANY, ANY) nc1.writer.pop_message('UBX', '*****@*****.**', ANY) nc2.writer.pop_message('ILN', 5, 'NLN', '*****@*****.**', ANY, ANY, ANY) nc2.writer.pop_message('UBX', '*****@*****.**', ANY) # User 1 starts convo nc1._l_xfr(1, 'SB') msg = nc1.writer.pop_message('XFR', 1, 'SB', ANY, 'CKI', ANY) token = msg[-1] sc1 = SBConn(sb, nb, MSNPWriter()) sc1._a_usr(0, '*****@*****.**', token) sc1.writer.pop_message('USR', 0, 'OK', '*****@*****.**', ANY) assert sc1.user.uuid == user1.uuid sc1._l_cal(1, 'doesnotexist') sc1.writer.pop_message(Err.InternalServerError, 1) sc1._l_cal(2, '*****@*****.**') sc1.writer.pop_message('CAL', 2, 'RINGING', ANY) msg = nc2.writer.pop_message('RNG', ANY, ANY, 'CKI', ANY, user1.email, ANY) sbsess_id = msg[1] token = msg[4] # User 2 joins convo sc2 = SBConn(sb, nb, MSNPWriter()) sc2._a_ans(0, '*****@*****.**', token, sbsess_id) sc2.writer.pop_message('IRO', 0, 1, 1, '*****@*****.**', ANY) sc2.writer.pop_message('ANS', 0, 'OK') sc1.writer.pop_message('JOI', '*****@*****.**', ANY) # User 1 sends message sc1._l_msg(3, 'A', b"my message") sc1.writer.pop_message('ACK', 3) sc2.writer.pop_message('MSG', '*****@*****.**', ANY, b"my message")
def test_create_event(self): s = Service(slug=u"hey", name=u"you", description=u"lol") s.put() stat = Status(name=u"you", slug=u"leave", description=u"why", image=u"cry") stat.put() e = Event(status=stat, service=s, message=u"¨¥¨œ∑´æ") e.put() data = e.rest("/api")
def xtest_ordered_list(self): u, p = self.make_profile('rowena') home = Link(url='htp://mysite/com', text='My Site', owner=p) flickr = Service(name='Flickr') flickr_pics = Link(service=flickr, text='More Photos', url='http://www.flickr.com/ropix', owner=p) picassa_pics = Link(text="Photos", url="http://www.picassa.com/ropix", owner=p) ll = ListOfLinks([home, flickr_pics, picassa_pics], p) self.assertEquals(len(ll), 3) self.assertEquals(ll[0], home)
def test_links(self): twitter = Service(name='twitter', url='http://www.twitter.com') u, p = self.make_profile('bob') link = Link(service=twitter, url='http://www.twitter.com/bob', text='@bob at Twitter', owner=p) link.save() self.assertEquals(count(get_links_for(p)), 1) link2 = Link(url='http://myblog.blogger.com', text='my blog', owner=p) link2.save() self.assertEquals(count(get_links_for(p)), 2)
def insert(username): """New Service""" form = ServiceForm(obj=request.json, prefix="service") form.category_ids.choices = CategoryHandler.list_for_select() if form.validate(): name = form.name.data description = form.description.data is_active = form.is_active.data category_ids = form.category_ids.data service = Service( username=username, name=name, description=description, is_active=is_active, updated=datetime.datetime.now(), created=datetime.datetime.now() ) db.session.add(service) try: db.session.commit() except: db.session.rollback() # return error message return {"error": "Error when adding an service"} # append the categories if len(category_ids) > 0: service.set_categoiry_ids(category_ids) try: db.session.commit() except: db.session.rollback() ServiceHandler.upload(service, form) # success, return new item return {"item": service.serialize()} # return form errors return {"errors": form.errors}
def on_post(self,request,response): # Get raw data from request body try: raw_data = request.stream.read() except Exception as ex: raise falcon.HTTPBadRequest(ex.message) # Jsonify the raw data try: data = json.loads(raw_data,encoding='utf-8') except ValueError: raise falcon.HTTPError(falcon.HTTP_400,'Unrecognized JSON','Unable to decode request body') # Return 404 if <tenant> does not exist if not data['tenant']: response.status = falcon.HTTP_404 return # Return 404 if <integration_type> does not exist if not data['integration_type']: response.status = falcon.HTTP_404 return # Validate data emptyValueKey = common.isEmpty(data['configuration']) if emptyValueKey: raise falcon.HTTPBadRequest('{} is missing'.format(emptyValueKey)) return emptyValueKey = common.isEmpty(data['configuration']['wsdl_urls']) if emptyValueKey: raise falcon.HTTPBadRequest('{} is missing'.format(emptyValueKey)) return # Query data from database result = Service.objects(tenant__iexact=data['tenant'], integration_type__iexact=data['integration_type']).exclude('id') ## No record found - insert new record. Else, update the existing record if result.count() < 1: new_config = Service(**data) new_config.save() else: result.modify(upsert=True, new=True, set__configuration=data['configuration']) # Response response.status = falcon.HTTP_200 response.body = result.to_json()