Skip to content
This repository has been archived by the owner on Mar 31, 2024. It is now read-only.

Commit

Permalink
Habilitar tests solo si existe la carpeta (#32)
Browse files Browse the repository at this point in the history
* deshabilitar CSpec si no está instalado

* feat: habilito tests solo si existe la carpeta

* docs: actualizo index.md y tests.md
  • Loading branch information
RaniAgus authored Apr 7, 2023
1 parent 00dbc45 commit ab5d9ab
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 73 deletions.
52 changes: 50 additions & 2 deletions docs/guia/avanzado/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ unitarios, desaconsejamos continuar con esta guía.

## Configuración del template

### Instalar CSpec

Para instalar CSpec, ejecutá en una terminal los siguientes comandos:

```bash
git clone https://github.com/mumuki/cspec.git
cd cspec
make
sudo make install
```
### Excluir archivos fuente

En caso de que estemos testeando un módulo con una función `main()`,
Expand Down Expand Up @@ -50,15 +60,53 @@ sí van a estar disponibles para ser testeadas.

### Agregar unit tests

Todas las test suites se guardan dentro de la carpeta `tests/`. El template ya
incluye una suite a modo de ejemplo:
Por último, para agregar tests a cualquier proyecto (ya sea ejecutable o
biblioteca), debemos hacerlo creando una carpeta `tests` a la misma altura que
`src`:

```bash
mkdir tests
```

Por ejemplo, partiendo del [proyecto base](../), podemos agregar un test inicial:

```bash
touch tests/example_test.c
```

```
.
├── makefile
├── settings.mk
├── src
│ └── main.c
└── tests
└── example_test.c
```


Con el siguiente código:

::: code-group

```c [example_test.c]
#include <stdio.h>
#include <stdbool.h>
#include <cspecs/cspec.h>

context (example) {
bool la_verdad = true;

describe("Hello world") {
it("la_verdad should be true") {
should_bool(la_verdad) be equal to(true);
} end
} end

}
```
:::
::: tip
Es una buena práctica replicar la estructura de archivos que tenemos en `src/`
Expand Down
31 changes: 4 additions & 27 deletions docs/guia/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,6 @@ import { repository, version } from '../../package.json'

# Primeros pasos

## Dependencias

Antes de empezar a utilizar los templates, necesitaremos instalar un framework
de Unit Testing llamado [CSpec](https://github.com/mumuki/cspec).

Para instalarlo, ejecutá en una terminal los siguientes comandos:

```bash
git clone https://github.com/mumuki/cspec.git
cd cspec
make
sudo make install
```

Esto tenés que hacerlo una sola vez por máquina. Si ya lo tenés
instalado, no hace falta volver a ejecutar estos comandos. :smile:

## Inicialización

Primero, vamos a descargar el template en una carpeta con el nombre del
Expand All @@ -44,10 +27,8 @@ tree .
.
├── makefile
├── settings.mk
├── src
│ └── main.c
└── tests
└── example_test.c
└── src
└── main.c
```

Una breve explicación de los archivos que hay en ella:
Expand All @@ -58,8 +39,6 @@ Una breve explicación de los archivos que hay en ella:
| `./settings.mk` | Configuración extra del proyecto (aprenderemos más a lo largo de la guía) |
| `./src/` | Carpeta en donde vamos a dejar todos los archivos fuente (.c y .h) del proyecto |
| `./src/main.c` | Archivo fuente en donde se encuentra la función `main` del proyecto |
| `./tests/` | Acá vamos a dejar todos unit tests del proyecto (más adelante veremos cómo hacerlo) |
| `./tests/example_test.c` | Un unit test a modo de ejemplo, podemos ignorarlo por ahora |

## Compilación

Expand All @@ -78,16 +57,15 @@ tree bin obj
```
.
├── bin
│ ├── {nombre-del-proyecto}.out
│ └── {nombre-del-proyecto}_tests.out
│ └── {nombre-del-proyecto}.out
└── obj
└── main.o
```

| Directorio | Descripción |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `./obj/` | Para cada archivo fuente en `src` se va a generar un objeto en código assembly con fines de acelerar el proceso de compilación. |
| `./bin/` | El compilador guarda aquí el ejecutable final y el ejecutable de los unit tests. |
| `./bin/` | El compilador guarda aquí el ejecutable final y el ejecutable de los unit tests (en caso de haber). |

::: tip

Expand All @@ -107,7 +85,6 @@ $ ls -l bin src
bin:
total 20
-rwxrwxr-x 1 utnso utnso 17256 Mar 12 11:43 ejemplo.out
-rwxrwxr-x 1 utnso utnso 17256 Mar 12 11:43 ejemplo_tests.out

src:
total 4
Expand Down
23 changes: 21 additions & 2 deletions src/compilation.mk
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
# Check if tests folder exists
ifneq ($(wildcard tests/*),)
TESTS_ENABLED=1
endif

# Set prerrequisites
SRCS_C += $(shell find src/ -iname "*.c")
SRCS_H += $(shell find src/ -iname "*.h")
TESTS_C += $(shell find tests/ -iname "*.c")
TESTS_H += $(shell find tests/ -iname "*.h")
DEPS = $(foreach SHL,$(SHARED_LIBPATHS),$(SHL:%=%/bin/lib$(notdir $(SHL)).so)) \
$(foreach STL,$(STATIC_LIBPATHS),$(STL:%=%/bin/lib$(notdir $(STL)).a))

# Set test prerrequisites
ifeq ($(TESTS_ENABLED),1)
TESTS_C += $(shell find tests/ -iname "*.c")
TESTS_H += $(shell find tests/ -iname "*.h")
endif

# Set header paths to (-I)nclude
IDIRS += $(addsuffix /src,$(SHARED_LIBPATHS) $(STATIC_LIBPATHS) .)

Expand All @@ -17,11 +26,19 @@ RUNDIRS = $(SHARED_LIBPATHS:%=$(shell cd . && pwd)/%/bin)

# Set intermediate objects
OBJS = $(patsubst src/%.c,obj/%.o,$(SRCS_C))

# Set test intermediate objects
ifeq ($(TESTS_ENABLED),1)
TEST_OBJS = $(TESTS_C) $(filter-out $(TEST_EXCLUDE), $(SRCS_C))
endif

# Set binary targets
BIN = bin/$(call filename,$(shell cd . && pwd | xargs basename))

# Set test binary targets
ifeq ($(TESTS_ENABLED),1)
TEST = bin/$(shell cd . && pwd | xargs basename)_tests.out
endif

.PHONY: all
all: CFLAGS = $(CDEBUG)
Expand All @@ -48,8 +65,10 @@ $(BIN): $(OBJS) | $(dir $(BIN))
obj/%.o: src/%.c $(SRCS_H) $(DEPS) | $(dir $(OBJS))
$(call compile_objs)

ifeq ($(TESTS_ENABLED),1)
$(TEST): $(TEST_OBJS) | $(dir $(TEST))
gcc $(CFLAGS) -o "$@" $^ $(IDIRS:%=-I%) $(LIBDIRS:%=-L%) $(RUNDIRS:%=-Wl,-rpath,%) $(LIBS:%=-l%) -lcspecs
endif

.SECONDEXPANSION:
$(DEPS): $$(shell find $$(patsubst %bin/,%src/,$$(dir $$@)) -iname "*.c") \
Expand Down
14 changes: 0 additions & 14 deletions src/project/tests/example_test.c

This file was deleted.

14 changes: 0 additions & 14 deletions src/shared/tests/example_test.c

This file was deleted.

14 changes: 0 additions & 14 deletions src/static/tests/example_test.c

This file was deleted.

2 changes: 2 additions & 0 deletions src/testing.mk
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
ifeq ($(TESTS_ENABLED),1)
.PHONY: test
test: all
valgrind --tool=none ./$(TEST)
Expand All @@ -16,3 +17,4 @@ test-memcheck: all
.PHONY: test-helgrind
test-helgrind: all
valgrind --tool=helgrind $(HELGRIND_FLAGS) ./$(TEST)
endif

0 comments on commit ab5d9ab

Please sign in to comment.