Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export provider=vbox/vmware
### <a name="backend-test"></a> Backend
1. Установка необходимых пакетов:
```bash
pyhton -m venv .venv
python -m venv .venv
source .venv/bin/activate
pip install -r back/requirements.txt
```
Expand Down
24 changes: 23 additions & 1 deletion front/src/miminet_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from os import urandom
import random
import json
from datetime import datetime

from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
Expand All @@ -10,6 +13,25 @@
import psycopg2


def generate_cosmic_name():
"""Generates unique cosmic object name with timestamp"""
try:
with open("static/cosmic_names.json", "r", encoding="utf-8") as f:
config = json.load(f)
except (FileNotFoundError, json.JSONDecodeError, KeyError):
config = {
"cosmic_objects": ["Звезда", "Галактика", "Планета"],
"prefixes": ["", "XB-", "NGC-"],
}

timestamp = datetime.now().strftime("%d%m%y")
random_num = random.randint(100, 999)
cosmic_type = random.choice(config["cosmic_objects"])
prefix = random.choice(config["prefixes"])

return f"{cosmic_type} {prefix}{timestamp}{random_num}"


convention = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
Expand Down Expand Up @@ -44,7 +66,7 @@ class Network(db.Model): # type:ignore[name-defined]
author_id = db.Column(BigInteger, ForeignKey("user.id"), nullable=False)

guid = db.Column(Text, nullable=False, unique=True)
title = db.Column(Text, default="Новая сеть", nullable=False)
title = db.Column(Text, default=lambda: generate_cosmic_name(), nullable=False)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут точно лямбда нужна? Нельзя просто default= generate_cosmic_name, если функцию передавать надо?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, иначе результат функции он кеширует и при создании сети каждый раз будет одно и то же название. Лямбда же позволяет при каждом создании сети вызывать функцию

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так если default= generate_cosmic_name использовать, мы тоже чисто функцию передаём, нет?


description = db.Column(Text, default="", nullable=True)

Expand Down
29 changes: 29 additions & 0 deletions front/src/static/cosmic_names.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"cosmic_objects": [
"Комета",
"Звезда",
"Галактика",
"Туманность",
"Спутник",
"Вселенная",
"Астероид",
"Планета",
"Метеорит",
"Квазар",
"Пульсар",
"Чёрная дыра",
"Суперновая",
"Созвездие",
"Космодром",
"Телескоп",
"Ракета",
"Орбита",
"Экзопланета",
"Космический корабль",
"Межзвёздный объект",
"Космическая станция",
"Темная материя",
"Космический зонд"
],
"prefixes": ["", "XB-", "NGC-", "HD-", "M-", "IC-", "PG-", "PSR-"]
}
6 changes: 4 additions & 2 deletions front/tests/test_network_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ def test_my_networks_button_press(self, selenium: Chrome):
assert selenium.current_url == HOME_PAGE

def test_new_network_existence(self, selenium: MiminetTester, empty_network: str):
"""Checks if the created network exists"""
"""Checks if the created network exists and has a unique generated name"""
selenium.get(empty_network) # open new network by URL
network_name = selenium.find_element(
By.CSS_SELECTOR, Location.Network.TITLE_LABEL.selector
).text

assert network_name == "Новая сеть"
assert network_name != ""
assert network_name != "Новая сеть"
assert len(network_name.split()) >= 1

def test_new_network_open(self, selenium: MiminetTester, empty_network: str):
"""Checks is it possible to open new network via home menu"""
Expand Down
Loading