Skip to content
Merged
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
36 changes: 36 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
DJANGO_SETTINGS_MODULE=suggestclasses.settings
ALLOWED_HOSTS='localhost, 127.0.0.1, labens.dct.ufrn.br'

SECRET_KEY='your-secret-key-here'
DEBUG=True

CSRF_COOKIE_SECURE=True

# CORS
CORS_ALLOW_ALL_ORIGINS=True
CORS_ALLOWED_ORIGINS="http://labens.dct.ufrn.br,https://labens.dct.ufrn.br,http://localhost:8003"
CSRF_TRUSTED_ORIGINS="http://labens.dct.ufrn.br,https://labens.dct.ufrn.br,http://localhost:8003"
SESSION_COOKIE_AGE=1800
SESSION_COOKIE_SECURE=True
SESSION_EXPIRE_AT_BROWSER_CLOSE=True
SECURE_CONTENT_TYPE_NOSNIFF=True
SECURE_BROWSER_XSS_FILTER=True

SECURE_SSL_REDIRECT=False
SECURE_HSTS_SECONDS=60
SECURE_HSTS_PRELOAD=True

DATABASE_NAME=scdb_dev
DATABASE_USER=sc_user
DATABASE_PASSWORD=sc_pass

DATABASE_HOST=localhost
DATABASE_PORT=5432

EMAIL_USER=your_email@example.com
EMAIL_PASS=your_email_password

PYTHONPATH=${PYTHONPATH}:/code:.

export DJANGO_SETTINGS_MODULE=suggestclasses.settings
export PYTHONPATH=${PYTHONPATH}:/data/projetos/suggestclasses
4 changes: 3 additions & 1 deletion .github/workflows/pythonapp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ jobs:
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Copying configurations
run: |
cp contrib/env-sample .env
cp .env.example .env
sed -i "s/^DATABASE_USER=.*/DATABASE_USER=postgres/" .env
sed -i "s/^DATABASE_PASSWORD=.*/DATABASE_PASSWORD=postgres/" .env
source .env
Comment thread
tacianosilva marked this conversation as resolved.
- name: Test with manage.py test
run: |
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ venv.bak/

dados/*.csv

path.env
/static/admin/
/static/css/
/static/js/
Expand Down
77 changes: 77 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Guide for Coding Agents

## Local environment

- Use the project virtual environment:

```bash
source .venv/bin/activate
```

- Create local configuration from the tracked template and load it before
running Django commands or data scripts:

```bash
cp .env.example .env
# Edit the values required by the local environment.
source .env
```

- Do not commit `.env`. It contains local credentials. Keep secrets only in
local environment files or in CI secrets.
- `DJANGO_SETTINGS_MODULE=suggestclasses.settings` and `PYTHONPATH` are set by
`.env`; there is no separate `path.env`.

## Database and tests

- The application reads the default database configuration from
`DATABASE_NAME`, `DATABASE_USER`, `DATABASE_PASSWORD`, `DATABASE_HOST`, and
`DATABASE_PORT`.
- No custom Django test database name is configured. Django uses
`test_<DATABASE_NAME>`; for example, `DATABASE_NAME=scdb_dev` uses
`test_scdb_dev`.
- To let Django create and remove test databases, grant the database role
`CREATEDB`:

```sql
ALTER ROLE sc_user WITH CREATEDB;
```

- On PostgreSQL 15+, ensure the role can create objects in the `public` schema
of the test database. In this environment, the role also needed `INHERIT`:

```sql
ALTER ROLE sc_user INHERIT;
```

- Run tests with:

```bash
python manage.py test --keepdb
```

`--keepdb` preserves the test database between executions.

## CI

- The GitHub Actions workflow copies `.env.example` to `.env` and then replaces
the database credentials with those of its PostgreSQL service
(`postgres`/`postgres`).
- Keep `.env.example` free of real credentials and compatible with the
variables read by `suggestclasses/settings.py`.

## Session changes recorded

- Removed the unused `DATABASE_TEST` variable. It was not read by the Django
settings, which rely on Django's default test database naming.
- Added `.env.example` at the repository root with placeholders for sensitive
values.
- Updated the README and CI workflow to use `.env.example`.
- Removed the obsolete `contrib/` directory and all `path.env` documentation.
- Removed the obsolete `contrib/` entry from `CONTRIBUTING.md` and the obsolete
`path.env` rule from `.gitignore`.
- The test database permission issue was reproduced and resolved locally after
granting `CREATEDB` and `INHERIT` to the database role.
- The test suite still has one unrelated pre-existing failure:
`core/tests/test_historico.py` uses removed `assertEquals`; use
`assertEqual` when addressing that test separately.
1 change: 0 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ Nosso documentação se concentra na pasta `docs/` deste repositório, aqui uma

| Arquivo/Pasta | Descrição |
|--- |--- |
| `contrib/` | Contém arquivos de configuração do ambiente de desenvolvimento.|
| `core/` | Aplicativo Django, código base de todo o sistema. |
| `dados/` | Contém scripts para downloads dos dados e povoamento da base de dados. |
| `docs/` | Contém arquivos de documentação e imagens da modelagem do Sistema. |
Expand Down
41 changes: 10 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,16 @@ Criação do Ambiente Virtual com [python3-venv](https://docs.python.org/pt-br/3
python3 -m venv .venv
```

Para ativar: ```source venv/bin/activate```.
Para ativar: ```source .venv/bin/activate```.
Para desativar: ```deactivate```.

Copie os exemplos destes arquivos no diretório raiz do projeto:
Copie o arquivo de exemplo para o diretório raiz do projeto:

```console
cp .env.sample .env
cp .env.example .env
```

Após editar os valores, execute os comandos:

Edite o arquivo `.env` para informar as variáveis e carregue-o:
```console
source .env
Comment thread
tacianosilva marked this conversation as resolved.
```
Expand Down Expand Up @@ -117,6 +116,8 @@ Lembre-se: O SGBD deve estar em execução e configure o acesso no arquivo `.env
O sistema é baseado nos dados abertos da UFRN, desta forma é necessário povoar o banco de dados
com informações de Horários, Centro, Salas, Departamentos, Componentes, etc.

Lembre-se de configurar e carregar todas as variáveis de ambiente com `source .env`.

A ordem é importante e deve ser seguida conforme descrito abaixo.

### Criar Grupos e Permissões
Expand Down Expand Up @@ -161,37 +162,15 @@ django.setup()
Configurações executar os testes:

```shell script
export DJANGO_SETTINGS_MODULE=suggestclasses.settings
python manage.py test
source .env
python manage.py test --keepdb
```

### Executar os Testes de Unidade e Cobertura

#### Utilizando o Cobetura

Primeiro defina a varíavel de ambiente: ```export DJANGO_SETTINGS_MODULE=projectname.settings```.

Depois instale o **coverage** e rode para ele gerar o arquivo `coverage.xml`.

```pythonstub
pip install coverage
coverage run -m unittest discover
coverage xml
```

Se usar `coverage html`, ele gera o relatório em html.

#### Utilizando Nose (desativado)

```shell script
pip install nose
pip install coverage
export DJANGO_SETTINGS_MODULE=suggestclasses.settings
```

```shell script
nosetests --with-xunit
nosetests --with-coverage --cover-package=core --cover-branches --cover-xml
source .env
coverage run manage.py test
```

## Executar o Sonar
Expand Down
26 changes: 0 additions & 26 deletions contrib/env-sample

This file was deleted.

2 changes: 0 additions & 2 deletions contrib/path.env-sample

This file was deleted.

39 changes: 0 additions & 39 deletions core/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from core.bo.historico import listar_historicos_by_discente
import io
import logging
from random import sample
from typing import List
from django.db.models.expressions import OuterRef, Subquery

# import matplotlib.pyplot as plt
from django.contrib import messages
from django.contrib.auth import authenticate, logout, login, update_session_auth_hash
from django.contrib.auth.decorators import login_required, permission_required
Expand All @@ -18,7 +15,6 @@
from django.template import loader
from django.views.decorators.http import require_http_methods
from django.views.generic import DetailView
# from matplotlib.backends.backend_agg import FigureCanvasAgg

from core.config.config import get_config
from core.models import Curso, ComponenteCurricular, EstruturaCurricular, SugestaoTurma, Sala, Docente, Turma, \
Expand Down Expand Up @@ -980,38 +976,3 @@ def enquete_votos_listar(request, pk, cc_pk):
}

return render(request, 'core/enquetes/votos_listar.html', context)




# def plot(request):
# # Creamos los datos para representar en el gráfico
# x = range(1, 11)
# y = sample(range(20), len(x))
#
# # Creamos una figura y le dibujamos el gráfico
# f = plt.figure()
#
# # Creamos los ejes
# axes = f.add_axes([0.15, 0.15, 0.75, 0.75]) # [left, bottom, width, height]
# axes.plot(x, y)
# axes.set_xlabel("Eje X")
# axes.set_ylabel("Eje Y")
# axes.set_title("Mi gráfico dinámico")

# # Como enviaremos la imagen en bytes la guardaremos en un buffer
# buf = io.BytesIO()
# canvas = FigureCanvasAgg(f)
# canvas.print_png(buf)

# # Creamos la respuesta enviando los bytes en tipo imagen png
# response = HttpResponse(buf.getvalue(), content_type='image/png')

# # Limpiamos la figura para liberar memoria
# f.clear()

# # Añadimos la cabecera de longitud de fichero para más estabilidad
# response['Content-Length'] = str(len(response.content))

# # Devolvemos la response
# return response
2 changes: 1 addition & 1 deletion suggestclasses/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
CORS_ALLOWED_ORIGINS = config('CORS_ALLOWED_ORIGINS', cast=Csv())
CSRF_TRUSTED_ORIGINS = config('CSRF_TRUSTED_ORIGINS', cast=Csv())

SESSION_COOKIE_AGE=60 * 30 # meia hora
SESSION_COOKIE_AGE = config('SESSION_COOKIE_AGE', default=60 * 30, cast=int)
SESSION_COOKIE_SECURE=config('SESSION_COOKIE_SECURE', default=False, cast=bool)
SESSION_EXPIRE_AT_BROWSER_CLOSE = config('SESSION_EXPIRE_AT_BROWSER_CLOSE', default=True, cast=bool)

Expand Down
Loading