def setUp(self): country = Country(name="Empire anarchique du Bachibouzouc", population=12000) country.save() region = Region(name="Province dépendante du Bazar", country=country) region.save() city1 = City(name="Trifouillis les Oies", region=region, country=country, location=Point(42, 127), population=42) city1.save() city2 = City(name="Montcuq", region=region, country=country, location=Point(42, 127), population=127) city2.save() data = { "username": "******", "email": "*****@*****.**", "password": "******" } response = self.client.post(register_url, data, format="json") data = { "username": "******", "password": "******", } response = self.client.post(login_url, data, format="json") token = response.data["auth_token"] self.client.credentials(HTTP_AUTHORIZATION='Token ' + token)
def setUp(self): country = Country(population=0) country.save() city1 = City( name='city1', name_std='city1....', country=country, location=Point(0, 0, srid=4326), population=0, ) city1.save() self.city2 = City( name='city2', name_std='city2....', country=country, location=Point(100, 100, srid=4326), population=0, ) self.city2.save() self.city3 = City( name='city3', name_std='city3....', country=country, location=Point(1000, -1000, srid=4326), population=0, ) self.city3.save()
def test_query_param_city_no_groups(self): City(name="Oslo") request = self.factory.get("/groups/", {"city": "Oslo"}) response = get_response(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data.get("results")), 0)
def test_model_city_duplicate(self): try: a_city = City(name='A') a_city.full_clean() except ValidationError as e: self.assertEqual( {'name': ['Город with this Город already exists.']}, e.message_dict)
def test_model_city_duplicate( self): # функция проверки дублирования назваия городов try: a_city = City(name='A') a_city.full_clean() except ValidationError as e: self.assertEqual( {'name': ['Город with this Город already exists.']}, e.message_dict)
def test_assert_correct_fields(self): """ The serializer should include only the name and search_name fields """ araras = City(code=1, name='Araras', search_name='araras') serializer_data = CitySerializer(araras).data self.assertEqual(5, len(serializer_data)) self.assertEqual('Araras', serializer_data['name']) self.assertEqual('araras', serializer_data['search_name']) self.assertEqual(1, serializer_data['code'])
def test_assert_correct_fields(self): """ The serializer should include only the name and search_name fields """ araras = City(code=1, name="Araras", search_name="araras") serializer_data = CitySerializer(araras).data self.assertEqual(5, len(serializer_data)) self.assertEqual("Araras", serializer_data["name"]) self.assertEqual("araras", serializer_data["search_name"]) self.assertEqual(1, serializer_data["code"])
def echo_server(my_port): sock = socket(AF_INET, SOCK_STREAM) # 소켓 객체를 생성 sock.bind( ('192.168.0.63', my_port)) # 소켓객체에 주소값을 바인딩 시킴 호스트와 포트로 된 튜플값을 인자로 받음 sock.listen(5) # 리스닝 수 = 5 print('server started') while True: # 프로세스가 죽을때 까지 conn, client_addr = sock.accept() # 서버소켓에 클라이언트가 연결되면 클라이언트 소켓, 주소를 반환 print('connected by', client_addr) # 어떤 주소에서 연결되었는지 프린트 try: while True: data = conn.recv(1024) #클라이언트로부터 1024바이트 만큼 데이터를 받아옴 if not data: break # 소켓이 닫힐때 까지 print('server received', data.decode()) r_msg = data.decode() s = r_msg.split() db = sqlite3.connect('temperature.db') cursor = db.cursor() # data type load if (s[0][5:] == 'load'): # 데이터타입이 load 이면 datein = (s[1][5:] + " " + s[2])[:19] # 날짜와 초 단위까지나오게 tmp = s[3][-5:] cursor.execute( "INSERT INTO TMP VALUES(?, ?);", (datein, tmp)) # 데이터 베이스에 값 datein, temperature값 저장 db.commit() msg = "server received\n" conn.send(msg.encode()) City(name=tmp, state=datein).save() db.close() # Exception Handling except OSError as e: print('socket error: ', e) except Exception as e: print('Exception at listening:'.format(e)) else: print('client closed', client_addr) finally: conn.close()
def load_cities(self, city_file): #Emply the City table self.delete_cities() errors = {} errors["data"] = [] errors["trailer"] = [] #Traverse the cities line by line count = 0 try: for line in city_file[:-1]: #Increment count to check against count += 1 city = {} finds = list(re.search('(.{20})(.{20})(.{2})', line).groups()) city["city_label"] = finds[0].strip() city["city_name"] = finds[1].strip() city["state"] = finds[2].strip() if not City.objects.filter(city_label=city["city_label"]): db_city = City(**city) db_city.save() else: error = "City label, {}, is a duplicate".format( city["city_label"]) log.error("error") errors["data"].append(error) except Exception as e: log.error(str(e)) errors["data"].append( "Please make sure your file if properly formatted") errors["trailer"] += self.load_trailer(city_file[-1], count) log.info("Cities Updated") return errors
def get_fallback_city(): return City(timezone=pytz.UTC, name='Ciudad No Identificada', country=Country(name='Pais No Identificado'))
def import_city(self): uptodate = self.download_once('city') if uptodate and not self.force: return data = self.get_data('city') self.build_country_index() self.build_region_index() self.logger.info("Importing city data") for item in data: if not self.call_hook('city_pre', item): continue if item['featureCode'] not in city_types: continue city = City() try: city.id = int(item['geonameid']) except: continue city.name = item['name'] city.kind = item['featureCode'] city.name_std = item['asciiName'] city.slug = slugify(city.name_std) city.location = Point(float(item['longitude']), float(item['latitude'])) city.population = int(item['population']) city.timezone = item['timezone'] try: city.elevation = int(item['elevation']) except: pass country_code = item['countryCode'] try: country = self.country_index[country_code] city.country = country except: self.logger.warning( "{0}: {1}: Cannot find country: {2} -- skipping".format( "CITY", city.name, country_code)) continue region_code = item['admin1Code'] try: region = self.region_index[country_code + "." + region_code] city.region = region except: self.logger.warning( "{0}: {1}: Cannot find region: {2} -- skipping".format( country_code, city.name, region_code)) continue subregion_code = item['admin2Code'] try: subregion = self.region_index[country_code + "." + region_code + "." + subregion_code] city.subregion = subregion except: if subregion_code: self.logger.warning( "{0}: {1}: Cannot find subregion: {2} -- skipping". format(country_code, city.name, subregion_code)) pass if not self.call_hook('city_post', city, item): continue city.save() self.logger.debug("Added city: {0}".format(city))
def test_create(self): test_city = City(name='Another City Name') self.assertEquals(test_city.name='Another City Name')
def test_model_city_duplicate(self): try: a_city = City(name='A') a_city.full_clean() except ValidationError as e: self.assertEqual({'name': ['Город с таким Город (один) уже существует.']}, e.message_dict)
def test_model_city_duplicate(self): city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
def test_modul_city_dublicate(self): # Тестирование возникновения ошибки при создании дубля города city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
import csv from cities.models import City with open('cities/cities.csv', newline='') as fp: reader = csv.reader(fp, delimiter='\t') header = next(reader) for row in reader: #print(row[1], row[2], row[3].replace(',','')) c = City(name=row[1], country_id=row[2], population=int(row[3].replace(',', ''))) c.save()
def test_model_city_duplicate(self): '''Тестирование при возникновении ошибок при создании дупликата города''' city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()
def test_model_city_duplicate(self): '''Тестирование возникновения ошибки при создании дубля города''' city = City(name="A") with self.assertRaises(ValidationError): city.full_clean()
import sqlite3 import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "citysearch_project.settings") django.setup() from cities.models import City conn = sqlite3.connect('temperature.db') c = conn.cursor() for row in c.execute('SELECT * FROM TMP'): City(name=row[0], state=row[1]).save() print(row)
def test_model_city_duplicate(self): '''Testing Cities for doppelgangers''' city = City(name='A') with self.assertRaises(ValidationError): city.full_clean()