Private
Public Access
eliminamos tests
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
3db4c9fe62
commit
65540d8425
12 files changed
-731
No files matched your search
@@ -1,49 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestActualizarObservacion_Validacion(t *testing.T) {
|
||||
texto := ""
|
||||
for i := 0; i < 61; i++ {
|
||||
texto += "a"
|
||||
}
|
||||
context, recorder := newStockContext(t, "PATCH", "/stock/1/observacion", map[string]any{
|
||||
"observacion": texto,
|
||||
}, gin.Params{{Key: "id", Value: "1"}})
|
||||
ctrl.ActualizarObservacion(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("observación larga: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "PATCH", "/stock/abc/observacion", map[string]any{
|
||||
"observacion": "ok",
|
||||
}, gin.Params{{Key: "id", Value: "abc"}})
|
||||
ctrl.ActualizarObservacion(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("id inválido: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActualizarObservacion_Integracion(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "PATCH", "/stock/1/observacion", map[string]any{
|
||||
"observacion": "test integracion",
|
||||
}, gin.Params{{Key: "id", Value: "1"}})
|
||||
ctrl.ActualizarObservacion(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("actualizar observación: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
context, recorder = newIntegrationContext(t, "PATCH", "/stock/1/observacion", map[string]any{
|
||||
"observacion": "",
|
||||
}, gin.Params{{Key: "id", Value: "1"}})
|
||||
ctrl.ActualizarObservacion(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("vaciar observación: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/models/contabilidad"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func TestAjustarStock_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "POST", "/stock/ajustes", map[string]any{}, nil)
|
||||
ctrl.AjustarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("ajuste sin datos: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "POST", "/stock/ajustes", map[string]any{
|
||||
"stockId": 1,
|
||||
"cantidadReal": -1,
|
||||
"motivo": "test",
|
||||
}, nil)
|
||||
ctrl.AjustarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("ajuste negativo: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "POST", "/stock/ajustes", map[string]any{
|
||||
"stockId": 1,
|
||||
"cantidadReal": 10,
|
||||
"motivo": "",
|
||||
}, nil)
|
||||
ctrl.AjustarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("ajuste sin motivo: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAjustarStock_Integracion(t *testing.T) {
|
||||
requireDB(t)
|
||||
|
||||
recibidos := make(chan map[string]any, 2)
|
||||
servidor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var cuerpo map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&cuerpo)
|
||||
recibidos <- cuerpo
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer servidor.Close()
|
||||
|
||||
t.Setenv("COMMS_URL", servidor.URL)
|
||||
t.Setenv("JWTString", "secreto-de-prueba")
|
||||
t.Setenv("STOCK_ALERT_EMAILS", "ops@example.com")
|
||||
|
||||
db := repositorios.BaseDeDatos()
|
||||
sufijo := fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
|
||||
marca := models.Marca{}
|
||||
if err := db.Where("empresa_id = ?", 1).First(&marca).Error; err != nil {
|
||||
marca = models.Marca{EmpresaID: 1, Nombre: "Marca test " + sufijo}
|
||||
if err := db.Create(&marca).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear la marca de prueba: %v", err)
|
||||
}
|
||||
defer func() { db.Unscoped().Delete(&models.Marca{}, marca.ID) }()
|
||||
}
|
||||
|
||||
repuesto := models.Repuesto{
|
||||
EmpresaID: 1,
|
||||
Nombre: "Repuesto test " + sufijo,
|
||||
Descripcion: "Descripcion test " + sufijo,
|
||||
Precio: 100,
|
||||
StockMinimo: 8,
|
||||
MarcaID: marca.ID,
|
||||
}
|
||||
if err := db.Create(&repuesto).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear el repuesto de prueba: %v", err)
|
||||
}
|
||||
defer func() { db.Unscoped().Delete(&models.Repuesto{}, repuesto.ID) }()
|
||||
|
||||
almacen := models.Almacen{}
|
||||
if err := db.Where("empresa_id = ?", 1).First(&almacen).Error; err != nil {
|
||||
t.Fatalf("no hay almacenes para la empresa 1: %v", err)
|
||||
}
|
||||
|
||||
stock := models.Stock{
|
||||
EmpresaID: 1,
|
||||
RepuestoID: uint64(repuesto.ID),
|
||||
AlmacenID: almacen.ID,
|
||||
Cantidad: 15,
|
||||
}
|
||||
if err := db.Create(&stock).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear el stock de prueba: %v", err)
|
||||
}
|
||||
defer func() { db.Unscoped().Delete(&models.Stock{}, stock.ID) }()
|
||||
defer func() { db.Unscoped().Where("stock_id = ?", stock.ID).Delete(&models.MovimientoStock{}) }()
|
||||
defer func() {
|
||||
var asientos []contabilidad.AsientoContable
|
||||
db.Where("comprobante_tipo = ? AND comprobante_id = ?", "AJUSTE", stock.ID).Find(&asientos)
|
||||
for _, asiento := range asientos {
|
||||
db.Unscoped().Where("asiento_id = ?", asiento.ID).Delete(&contabilidad.MovimientoContable{})
|
||||
db.Unscoped().Delete(&contabilidad.AsientoContable{}, asiento.ID)
|
||||
}
|
||||
}()
|
||||
|
||||
context, recorder := newIntegrationContext(t, "POST", "/stock/ajustes", map[string]any{
|
||||
"stockId": stock.ID,
|
||||
"cantidadReal": 2,
|
||||
"motivo": "Error de conteo",
|
||||
"observacion": "prueba de stock bajo",
|
||||
}, nil)
|
||||
ctrl.AjustarStock(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("ajuste bajo mínimo: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
actualizado := models.Stock{}
|
||||
if err := db.First(&actualizado, stock.ID).Error; err != nil {
|
||||
t.Fatalf("no se pudo releer el stock: %v", err)
|
||||
}
|
||||
if actualizado.Cantidad != 2 {
|
||||
t.Fatalf("cantidad: esperado 2, obtenido %.3f", actualizado.Cantidad)
|
||||
}
|
||||
|
||||
var movimiento models.MovimientoStock
|
||||
if err := db.Where("stock_id = ? AND tipo = ?", stock.ID, models.MovimientoAjuste).First(&movimiento).Error; err != nil {
|
||||
t.Fatalf("no se encontró el movimiento de ajuste: %v", err)
|
||||
}
|
||||
if movimiento.SaldoAnterior != 15 || movimiento.SaldoPosterior != 2 {
|
||||
t.Fatalf("saldos inesperados: anterior %.3f, posterior %.3f", movimiento.SaldoAnterior, movimiento.SaldoPosterior)
|
||||
}
|
||||
|
||||
select {
|
||||
case cuerpo := <-recibidos:
|
||||
if cuerpo["titulo"] != "Stock bajo mínimo: "+repuesto.Nombre {
|
||||
t.Fatalf("título de la alerta inesperado: %v", cuerpo["titulo"])
|
||||
}
|
||||
destinatarios, _ := cuerpo["to"].([]any)
|
||||
if len(destinatarios) != 1 || destinatarios[0] != "ops@example.com" {
|
||||
t.Fatalf("destinatarios inesperados: %v", cuerpo["to"])
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("no se envió la notificación de stock bajo")
|
||||
}
|
||||
|
||||
context, recorder = newIntegrationContext(t, "POST", "/stock/ajustes", map[string]any{
|
||||
"stockId": stock.ID,
|
||||
"cantidadReal": 12,
|
||||
"motivo": "Error de conteo",
|
||||
}, nil)
|
||||
ctrl.AjustarStock(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("ajuste sobre el mínimo: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
select {
|
||||
case cuerpo := <-recibidos:
|
||||
t.Fatalf("no debería notificarse un ajuste sobre el mínimo: %v", cuerpo["titulo"])
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"repuestera_back/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var dbAvailable bool
|
||||
|
||||
func newStockContext(t *testing.T, method, path string, body any, params gin.Params) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
var payload []byte
|
||||
if body != nil {
|
||||
payload, _ = json.Marshal(body)
|
||||
}
|
||||
request, err := http.NewRequest(method, path, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("no se pudo crear la request: %v", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
context.Request = request
|
||||
context.Params = params
|
||||
context.Set("userID", uint(1))
|
||||
context.Set(utils.ContextEmpresaIDKey, uint(0))
|
||||
return context, recorder
|
||||
}
|
||||
|
||||
func newIntegrationContext(t *testing.T, method, path string, body any, params gin.Params) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if !dbAvailable {
|
||||
t.Skip("base de datos no disponible")
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
var payload []byte
|
||||
if body != nil {
|
||||
payload, _ = json.Marshal(body)
|
||||
}
|
||||
request, err := http.NewRequest(method, path, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("no se pudo crear la request: %v", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
context.Request = request
|
||||
context.Params = params
|
||||
context.Set("userID", uint(1))
|
||||
context.Set(utils.ContextEmpresaIDKey, uint(1))
|
||||
return context, recorder
|
||||
}
|
||||
|
||||
func requireDB(t *testing.T) {
|
||||
if !dbAvailable {
|
||||
t.Skip("base de datos no disponible")
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestIngresarStock_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "POST", "/stock/ingresos", map[string]any{
|
||||
"proveedorId": 1,
|
||||
"numero": "TEST",
|
||||
"fechaEmision": "2026-01-01T00:00:00Z",
|
||||
"almacenDestinoId": 1,
|
||||
"items": []any{},
|
||||
}, nil)
|
||||
ctrl.IngresarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("ingreso sin items: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "POST", "/stock/ingresos", map[string]any{}, nil)
|
||||
ctrl.IngresarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("ingreso vacío: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/repositorios"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestLiberarReserva_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "PATCH", "/stock/reservas/abc/liberar", nil, gin.Params{{Key: "id", Value: "abc"}})
|
||||
ctrl.LiberarReserva(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("liberar id inválido: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiberarReserva_Inexistente(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "PATCH", "/stock/reservas/2147483000/liberar", nil, gin.Params{{Key: "id", Value: "2147483000"}})
|
||||
ctrl.LiberarReserva(context)
|
||||
|
||||
if recorder.Code != 404 {
|
||||
t.Fatalf("liberar reserva inexistente: esperado 404, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "reserva inexistente") {
|
||||
t.Fatalf("liberar reserva inexistente: respuesta inesperada: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiberarReserva_Integracion(t *testing.T) {
|
||||
reserva, stock, limpiar := crearReservaActivaParaLiberar(t, 3)
|
||||
defer limpiar()
|
||||
|
||||
context, recorder := newIntegrationContext(
|
||||
t,
|
||||
"PATCH",
|
||||
fmt.Sprintf("/stock/reservas/%d/liberar", reserva.ID),
|
||||
nil,
|
||||
gin.Params{{Key: "id", Value: fmt.Sprintf("%d", reserva.ID)}},
|
||||
)
|
||||
ctrl.LiberarReserva(context)
|
||||
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("liberar reserva: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
db := repositorios.BaseDeDatos()
|
||||
actualizada := models.Reserva{}
|
||||
if err := db.First(&actualizada, reserva.ID).Error; err != nil {
|
||||
t.Fatalf("no se pudo releer la reserva: %v", err)
|
||||
}
|
||||
if actualizada.Estado != models.ReservaLiberada {
|
||||
t.Fatalf("estado de la reserva: esperado %q, obtenido %q", models.ReservaLiberada, actualizada.Estado)
|
||||
}
|
||||
|
||||
stockActualizado := models.Stock{}
|
||||
if err := db.First(&stockActualizado, stock.ID).Error; err != nil {
|
||||
t.Fatalf("no se pudo releer el stock: %v", err)
|
||||
}
|
||||
if stockActualizado.CantidadReservada != 0 {
|
||||
t.Fatalf("cantidad reservada: esperado 0, obtenido %.3f", stockActualizado.CantidadReservada)
|
||||
}
|
||||
|
||||
var movimientos int64
|
||||
if err := db.Model(&models.MovimientoStock{}).
|
||||
Where("stock_id = ? AND tipo = ? AND referencia_tipo = ? AND referencia_id = ?", stock.ID, models.MovimientoLiberacion, "RESERVA", reserva.ID).
|
||||
Count(&movimientos).Error; err != nil {
|
||||
t.Fatalf("no se pudieron contar los movimientos: %v", err)
|
||||
}
|
||||
if movimientos != 1 {
|
||||
t.Fatalf("movimientos de liberación: esperado 1, obtenido %d", movimientos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiberarReserva_DobleLiberacion(t *testing.T) {
|
||||
reserva, stock, limpiar := crearReservaActivaParaLiberar(t, 3)
|
||||
defer limpiar()
|
||||
|
||||
params := gin.Params{{Key: "id", Value: fmt.Sprintf("%d", reserva.ID)}}
|
||||
path := fmt.Sprintf("/stock/reservas/%d/liberar", reserva.ID)
|
||||
|
||||
context, recorder := newIntegrationContext(t, "PATCH", path, nil, params)
|
||||
ctrl.LiberarReserva(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("primera liberación: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
context, recorder = newIntegrationContext(t, "PATCH", path, nil, params)
|
||||
ctrl.LiberarReserva(context)
|
||||
if recorder.Code != 409 {
|
||||
t.Fatalf("segunda liberación: esperado 409, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
db := repositorios.BaseDeDatos()
|
||||
stockActualizado := models.Stock{}
|
||||
if err := db.First(&stockActualizado, stock.ID).Error; err != nil {
|
||||
t.Fatalf("no se pudo releer el stock: %v", err)
|
||||
}
|
||||
if stockActualizado.CantidadReservada != 0 {
|
||||
t.Fatalf("cantidad reservada tras doble liberación: esperado 0, obtenido %.3f", stockActualizado.CantidadReservada)
|
||||
}
|
||||
|
||||
var movimientos int64
|
||||
if err := db.Model(&models.MovimientoStock{}).
|
||||
Where("stock_id = ? AND tipo = ? AND referencia_tipo = ? AND referencia_id = ?", stock.ID, models.MovimientoLiberacion, "RESERVA", reserva.ID).
|
||||
Count(&movimientos).Error; err != nil {
|
||||
t.Fatalf("no se pudieron contar los movimientos: %v", err)
|
||||
}
|
||||
if movimientos != 1 {
|
||||
t.Fatalf("movimientos de liberación tras doble liberación: esperado 1, obtenido %d", movimientos)
|
||||
}
|
||||
}
|
||||
|
||||
// crearReservaActivaParaLiberar arma un stock con cantidad reservada y una
|
||||
// reserva activa para poder ejercitar la liberación sin depender de datos
|
||||
// precargados.
|
||||
func crearReservaActivaParaLiberar(t *testing.T, cantidad float64) (models.Reserva, models.Stock, func()) {
|
||||
t.Helper()
|
||||
requireDB(t)
|
||||
|
||||
db := repositorios.BaseDeDatos()
|
||||
sufijo := fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
|
||||
var marca models.Marca
|
||||
marcaCreada := false
|
||||
if err := db.Where("empresa_id = ?", 1).First(&marca).Error; err != nil {
|
||||
marca = models.Marca{EmpresaID: 1, Nombre: "Marca liberar " + sufijo}
|
||||
if err := db.Create(&marca).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear la marca de prueba: %v", err)
|
||||
}
|
||||
marcaCreada = true
|
||||
}
|
||||
|
||||
repuesto := models.Repuesto{
|
||||
EmpresaID: 1,
|
||||
Nombre: "Repuesto liberar " + sufijo,
|
||||
Descripcion: "Descripcion liberar " + sufijo,
|
||||
Precio: 100,
|
||||
StockMinimo: 1,
|
||||
MarcaID: marca.ID,
|
||||
}
|
||||
if err := db.Create(&repuesto).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear el repuesto de prueba: %v", err)
|
||||
}
|
||||
|
||||
almacen := models.Almacen{}
|
||||
if err := db.Where("empresa_id = ?", 1).First(&almacen).Error; err != nil {
|
||||
t.Fatalf("no hay almacenes para la empresa 1: %v", err)
|
||||
}
|
||||
|
||||
cliente := models.Cliente{
|
||||
EmpresaID: 1,
|
||||
Nombre: "Cliente liberar " + sufijo,
|
||||
Cuit: fmt.Sprintf("9%010d", time.Now().UnixNano()%10000000000),
|
||||
}
|
||||
if err := db.Create(&cliente).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear el cliente de prueba: %v", err)
|
||||
}
|
||||
|
||||
stock := models.Stock{
|
||||
EmpresaID: 1,
|
||||
RepuestoID: uint64(repuesto.ID),
|
||||
AlmacenID: almacen.ID,
|
||||
Cantidad: 10,
|
||||
CantidadReservada: cantidad,
|
||||
}
|
||||
if err := db.Create(&stock).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear el stock de prueba: %v", err)
|
||||
}
|
||||
|
||||
reserva := models.Reserva{
|
||||
EmpresaID: 1,
|
||||
RepuestoID: repuesto.ID,
|
||||
AlmacenID: almacen.ID,
|
||||
Cantidad: cantidad,
|
||||
Estado: models.ReservaActiva,
|
||||
ClienteID: &cliente.ID,
|
||||
CreadoPorID: 1,
|
||||
}
|
||||
if err := db.Create(&reserva).Error; err != nil {
|
||||
t.Fatalf("no se pudo crear la reserva de prueba: %v", err)
|
||||
}
|
||||
|
||||
limpiar := func() {
|
||||
db.Unscoped().Where("stock_id = ?", stock.ID).Delete(&models.MovimientoStock{})
|
||||
db.Unscoped().Delete(&models.Reserva{}, reserva.ID)
|
||||
db.Unscoped().Delete(&models.Stock{}, stock.ID)
|
||||
db.Unscoped().Delete(&models.Repuesto{}, repuesto.ID)
|
||||
db.Unscoped().Delete(&models.Cliente{}, cliente.ID)
|
||||
if marcaCreada {
|
||||
db.Unscoped().Delete(&models.Marca{}, marca.ID)
|
||||
}
|
||||
}
|
||||
|
||||
return reserva, stock, limpiar
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestObtenerReservas_Integracion(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "GET", "/stock/reservas", nil, nil)
|
||||
ctrl.ObtenerReservas(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("obtener reservas: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestObtenerStock_Integracion(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "GET", "/stock/", nil, nil)
|
||||
ctrl.ObtenerStock(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("obtener stock: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestObtenerStockPorID_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "GET", "/stock/abc", nil, gin.Params{{Key: "id", Value: "abc"}})
|
||||
ctrl.ObtenerStockPorID(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("id inválido: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObtenerStockPorID_Integracion(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "GET", "/stock/1", nil, gin.Params{{Key: "id", Value: "1"}})
|
||||
ctrl.ObtenerStockPorID(context)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("obtener stock por id: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestRegistrarDevolucion_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "POST", "/stock/devoluciones", map[string]any{
|
||||
"facturaId": 1,
|
||||
"motivo": "test",
|
||||
"items": []any{},
|
||||
}, nil)
|
||||
ctrl.RegistrarDevolucion(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("devolución sin items: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "POST", "/stock/devoluciones", map[string]any{}, nil)
|
||||
ctrl.RegistrarDevolucion(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("devolución vacía: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestReservarStock_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "POST", "/stock/reservas", map[string]any{
|
||||
"repuestoId": 1,
|
||||
"almacenId": 1,
|
||||
"cantidad": 1,
|
||||
}, nil)
|
||||
ctrl.ReservarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("reserva sin cliente: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "POST", "/stock/reservas", map[string]any{
|
||||
"repuestoId": 1,
|
||||
"almacenId": 1,
|
||||
"cantidad": 0,
|
||||
"clienteId": 1,
|
||||
}, nil)
|
||||
ctrl.ReservarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("reserva cantidad cero: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestObtenerReservas_EstadoInvalido(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "GET", "/stock/reservas?estado=invalido", nil, nil)
|
||||
ctrl.ObtenerReservas(context)
|
||||
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("estado inválido: esperado 400, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestObtenerReservas_Filtros(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(
|
||||
t,
|
||||
"GET",
|
||||
"/stock/reservas?estado=activa&q=bujia&cliente=garcia&almacenId=1&pagina=1&porPagina=20",
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
ctrl.ObtenerReservas(context)
|
||||
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("reservas con filtros: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if !json.Valid(recorder.Body.Bytes()) {
|
||||
t.Fatalf("reservas con filtros: respuesta no es JSON válido: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestObtenerReservas_TodasLasEstados(t *testing.T) {
|
||||
context, recorder := newIntegrationContext(t, "GET", "/stock/reservas?estado=todas", nil, nil)
|
||||
ctrl.ObtenerReservas(context)
|
||||
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("reservas de todos los estados: esperado 200, obtenido %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"repuestera_back/config"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
_ = godotenv.Load("../../.env")
|
||||
if dbString := os.Getenv("DBSTRING"); dbString != "" {
|
||||
os.Setenv("DBSTRING", strings.ReplaceAll(dbString, "mysql:3306", "localhost:3306"))
|
||||
}
|
||||
if err := config.InitDB(); err == nil && config.DB != nil {
|
||||
repositorios.InicializarRepositorios(config.DB)
|
||||
dbAvailable = true
|
||||
} else {
|
||||
repositorios.InicializarRepositorios(nil)
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestStockSuite(t *testing.T) {
|
||||
t.Run("ActualizarObservacion/Validacion", TestActualizarObservacion_Validacion)
|
||||
t.Run("AjustarStock/Validacion", TestAjustarStock_Validacion)
|
||||
t.Run("IngresarStock/Validacion", TestIngresarStock_Validacion)
|
||||
t.Run("LiberarReserva/Validacion", TestLiberarReserva_Validacion)
|
||||
t.Run("ReservarStock/Validacion", TestReservarStock_Validacion)
|
||||
t.Run("RegistrarDevolucion/Validacion", TestRegistrarDevolucion_Validacion)
|
||||
t.Run("TrasladarStock/Validacion", TestTrasladarStock_Validacion)
|
||||
t.Run("ObtenerStockPorID/Validacion", TestObtenerStockPorID_Validacion)
|
||||
|
||||
if !dbAvailable {
|
||||
t.Skip("base de datos no disponible para tests de integración")
|
||||
}
|
||||
t.Run("ActualizarObservacion/Integracion", TestActualizarObservacion_Integracion)
|
||||
t.Run("AjustarStock/Integracion", TestAjustarStock_Integracion)
|
||||
t.Run("LiberarReserva/Integracion", TestLiberarReserva_Integracion)
|
||||
t.Run("LiberarReserva/Inexistente", TestLiberarReserva_Inexistente)
|
||||
t.Run("LiberarReserva/DobleLiberacion", TestLiberarReserva_DobleLiberacion)
|
||||
t.Run("ObtenerReservas/Integracion", TestObtenerReservas_Integracion)
|
||||
t.Run("ObtenerStock/Integracion", TestObtenerStock_Integracion)
|
||||
t.Run("ObtenerStockPorID/Integracion", TestObtenerStockPorID_Integracion)
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ctrl "repuestera_back/controllers/stock"
|
||||
)
|
||||
|
||||
func TestTrasladarStock_Validacion(t *testing.T) {
|
||||
context, recorder := newStockContext(t, "POST", "/stock/traslados", map[string]any{}, nil)
|
||||
ctrl.TrasladarStock(context)
|
||||
if recorder.Code != 400 {
|
||||
t.Fatalf("traslado sin datos: esperado 400, obtenido %d", recorder.Code)
|
||||
}
|
||||
|
||||
context, recorder = newStockContext(t, "POST", "/stock/traslados", map[string]any{
|
||||
"repuestoId": 1,
|
||||
"almacenOrigenId": 1,
|
||||
"almacenDestinoId": 1,
|
||||
"cantidad": 1,
|
||||
}, nil)
|
||||
ctrl.TrasladarStock(context)
|
||||
if recorder.Code != 422 {
|
||||
t.Fatalf("traslado mismo almacén: esperado 422, obtenido %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user